Skip to content

Instantly share code, notes, and snippets.

@brunophilipe
Last active July 4, 2018 21:10
Show Gist options
  • Save brunophilipe/6a17e853f0667ef216f3ce0124827424 to your computer and use it in GitHub Desktop.
Save brunophilipe/6a17e853f0667ef216f3ce0124827424 to your computer and use it in GitHub Desktop.
Type-safe segues in Swift 4
import UIKit
/// A Segue is a type-safe form of a UI segue.
protocol Segue
{
/// The identifier of this segue
var identifier: String { get }
}
extension UIViewController
{
/// Perform a type-safe segue, optionally proviing a sender object.
func performSegue(_ segue: Segue, sender: Any?)
{
self.performSegue(withIdentifier: segue.identifier, sender: sender)
}
}
/// Automatically synthesizes identifiers from the raw value of entities that conform
/// to both RawRepresentable and Segue
extension Segue where Self: RawRepresentable, Self.RawValue == String
{
var identifier: String
{
return rawValue
}
}
class ViewController: UIViewController
{
/// List of segues that are registered for this view controller.
internal enum Segues: String, Segue
{
case showDetail, embedEventsList, embedCalendar
}
/// Invoked by some other entity to request the presentation of an event.
func showDetail(for event: Event)
{
/// Invoke a type-safe segue.
performSegue(Segues.showDetail, sender: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment