Skip to content

Instantly share code, notes, and snippets.

@roman-wb
Last active January 25, 2019 06:29
Show Gist options
  • Select an option

  • Save roman-wb/1107af17cbce08f2cc024d30b0ab6c1b to your computer and use it in GitHub Desktop.

Select an option

Save roman-wb/1107af17cbce08f2cc024d30b0ab6c1b to your computer and use it in GitHub Desktop.
Extension for instance Storyboard one Controller
// 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