Forked from christianhatch/storyboard-viewcontroller-init.swift
Created
January 13, 2017 09:55
-
-
Save JaleelNazir/3a116842f814d64f5c071deed4c80cea to your computer and use it in GitHub Desktop.
A simple UIStoryboard extension to easily instantiate viewcontrollers using Swift type casting. Raw
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Do you often find yourself writing lines of code that look like this? | |
// let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ViewController") as! ViewController | |
// Here's a simpler way, using generics and Swift type-casting (as long as the viewcontroller's storyboard identifier is its class name). | |
// Now you can write: let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController() as ViewController | |
extension UIStoryboard { | |
func instantiateViewController<T: UIViewController>() -> T { | |
guard let vc = instantiateViewControllerWithIdentifier(String(T)) as? T else { | |
fatalError("Could not locate viewcontroller with with identifier \(String(T)) in storyboard.") | |
} | |
return vc | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment