Last active
September 3, 2018 13:15
-
-
Save gragera/fab8a2eaa11dc63b9b9f to your computer and use it in GitHub Desktop.
Using swift generics for easier storyboard ViewController instantiation
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
import UIKit | |
extension UIStoryboard { | |
func instantiate<T>(identifier: String, asClass: T.Type) -> T { | |
return instantiateViewControllerWithIdentifier(identifier) as! T | |
} | |
func instantiate<T>(identifier: String) -> T { | |
return instantiateViewControllerWithIdentifier(identifier) as! T | |
} | |
} | |
// Usage | |
let vc = storyboard.instantiate("MyViewControllerIdentifier", asClass: MyViewController.self) | |
// or | |
let vc2: MyViewController = storyboard.instantiate("MyViewControllerIdentifier") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
allows me to do:
But I actually think that:
should work (or at least I think so), but it doesn't.
I think I still prefer not to “manually” specify the class in the argument if I can. Any of the other options is more idiomatic.