Last active
January 27, 2022 22:27
-
-
Save christianhatch/442a2ce232f17e4d7172535bafacd640 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 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
My take: