Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JaleelNazir/3a116842f814d64f5c071deed4c80cea to your computer and use it in GitHub Desktop.
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
// 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