Last active
January 25, 2019 06:29
-
-
Save roman-wb/1107af17cbce08f2cc024d30b0ab6c1b to your computer and use it in GitHub Desktop.
Extension for instance Storyboard one Controller
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
| // Variant 1 | |
| extension UIViewController { | |
| static func instance<T: UIViewController>() -> T? { | |
| let name = String(describing: self) | |
| let storyboard = UIStoryboard(name: name, bundle: nil) | |
| let controller = storyboard.instantiateViewController(withIdentifier: name) | |
| return controller as? T | |
| } | |
| } | |
| // Required init type `vc` else compilator not understand return type | |
| guard let vc: VC = VC.instance() else { return } | |
| // Variant 2 | |
| extension UIViewController { | |
| private class func instancePrivate<T: UIViewController>() -> T? { | |
| let name = String(describing: self) | |
| let storyboard = UIStoryboard(name: name, bundle: nil) | |
| return storyboard.instantiateInitialViewController(withIdentifier: name) as? T | |
| } | |
| class func instance() -> Self? { | |
| return instancePrivate() | |
| } | |
| } | |
| // Vairant 3 | |
| // Source https://gist.github.com/hamsternik/bf2ab86cd0f3fa3e1ccad69cb09e53bd | |
| extension UIViewController { | |
| private class func storyboardInstancePrivate<T: UIViewController>() -> T? { | |
| let storyboard = UIStoryboard(name: String(describing: self), bundle: nil) | |
| return storyboard.instantiateInitialViewController() as? T | |
| } | |
| class func storyboardInstance() -> Self? { | |
| return storyboardInstancePrivate() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment