Skip to content

Instantly share code, notes, and snippets.

@grosch
Last active October 28, 2017 01:25
Show Gist options
  • Save grosch/539fc25cb66b33d4f595 to your computer and use it in GitHub Desktop.
Save grosch/539fc25cb66b33d4f595 to your computer and use it in GitHub Desktop.
Segue Handler
#if os(iOS)
import UIKit
typealias _ViewController = UIViewController
typealias _StoryboardSegue = UIStoryboardSegue
#else
import Cocoa
typealias _ViewController = NSViewController
typealias _StoryboardSegue = NSStoryboardSegue
#endif
/**
* A protocol that represents a segue identifier in the storyboard. Every view controller that
* inherits this protocol should define the `SegueIdentifier` enum to be of type `String`, and
* there should be a case name that **exactly** matches what is in the storyboard.
*
* ```swift
* class SomeViewController : UIViewController, SegueHandlerType {
* enum SegueIdentifier : String {
* case ShowSomething, ReturnHome
* }
*
* override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
* guard let ident = segueIdentifier(for: segue) else { return }
*
* switch ident {
* case .ShowSomething: ...
* case .ReturnHome: ...
* }
* }
*
* @IBAction private someAction() {
* ...
* performSegue(withIdentifier: .ShowSomething, sender: self)
* }
* }
*/
@available(iOS 9.0, OSX 10.10, *)
protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
@available(iOS 9.0, OSX 10.10, *)
extension SegueHandlerType where Self: _ViewController, SegueIdentifier.RawValue == String {
func performSegue(withIdentifier identifier: SegueIdentifier, sender: Any?) {
performSegue(withIdentifier: identifier.rawValue, sender: sender)
}
func segueIdentifier(for segue: _StoryboardSegue) -> SegueIdentifier? {
// It's quite possible to have no identifier.
guard let identifier = segue.identifier else { return nil }
return SegueIdentifier(rawValue: identifier)
}
func shouldPerformSegue(withIdentifier identifier: SegueIdentifier, sender: Any?) -> Bool {
return shouldPerformSegue(withIdentifier: identifier.rawValue, sender: sender)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment