Skip to content

Instantly share code, notes, and snippets.

@denisoliveira
Created November 26, 2020 05:10
Show Gist options
  • Save denisoliveira/9f3f4bd86813d3a1b92885f6fe146ae4 to your computer and use it in GitHub Desktop.
Save denisoliveira/9f3f4bd86813d3a1b92885f6fe146ae4 to your computer and use it in GitHub Desktop.
Segueable a type safe segue on Swift like Codable protocol
protocol SegueKey {
var identifier: String { get }
}
extension SegueKey where Self: RawRepresentable, Self.RawValue == String {
var identifier: String {
return rawValue
}
}
protocol Segueable {
associatedtype SegueKeys: RawRepresentable where SegueKeys: SegueKey
func segueIdentifierKey(for segue: UIStoryboardSegue) -> SegueKeys
}
extension Segueable where Self: UIViewController, SegueKeys.RawValue == String {
func segueIdentifierKey(for segue: UIStoryboardSegue) -> SegueKeys {
guard let identifierKey = segue.identifier.flatMap(SegueKeys.init) else {
fatalError("Couldn't map segue identifier -- \(segue.identifier ?? "nil") -- to segue key")
}
return identifierKey
}
func performSegue(_ segue: SegueKeys, sender: Any?) {
self.performSegue(withIdentifier: segue.identifier, sender: sender)
}
}
class ViewController: UIViewController, Segueable {
enum SegueKeys: String, SegueKey {
case toDescription
case toDetails
case unnamed
}
override func viewDidLoad() {
super.viewDidLoad()
performSegue(.toDescription, sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segueIdentifierKey(for: segue) {
case .toDescription: break
case .toDetails: break
case .unnamed: break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment