Skip to content

Instantly share code, notes, and snippets.

@benaneesh
Created May 9, 2016 19:19
Show Gist options
  • Select an option

  • Save benaneesh/04e067bc450201ca3b9f3fc3667a8ae0 to your computer and use it in GitHub Desktop.

Select an option

Save benaneesh/04e067bc450201ca3b9f3fc3667a8ae0 to your computer and use it in GitHub Desktop.
extension UIStoryboard {
enum Storyboard : String {
case Main
case News
case Gallery
}
/**
Better convenience initializer to hide ugly code
- Usage: let storyboard = UIStoryboard(storyboard: .Main)
*/
convenience init(storyboard: Storyboard, bundle: NSBundle? = nil) {
self.init(name: storyboard.rawValue, bundle: bundle)
}
/**
Convenience function that uses `StoryboardIdentifiable` (see below) to instantiate
a specific type of view controller through UIStoryboard functions without typecasting.
Helps avoid unsafe string literals too.
- Usage: let viewController: MyViewController = storyboard.instantiateViewController()
- Returns: Instance of UIViewController.
*/
func instantiateViewController<T: UIViewController where T: StoryboardIdentifiable>() -> T {
let optionalViewController = self.instantiateViewControllerWithIdentifier(T.storyboardIdentifier)
guard let viewController = optionalViewController as? T else {
fatalError("Couldn’t instantiate view controller with identifier \(T.storyboardIdentifier) ")
}
return viewController
}
}
/**
Protocol which gives any class that conforms to it, a static variable, storyboardIdentifier.
Reduces the amount of work we have to do when managing identifiers for view controllers.
Extend it only for UIViewController (or subclasses), so now we have a method to get the
storyboardIdentifier string dynamically from the class at runtime.
*/
protocol StoryboardIdentifiable {
static var storyboardIdentifier: String { get }
}
extension StoryboardIdentifiable where Self: UIViewController {
static var storyboardIdentifier: String {
return String(self)
}
}
extension UIViewController : StoryboardIdentifiable { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment