Skip to content

Instantly share code, notes, and snippets.

@gragera
Last active September 3, 2018 13:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gragera/fab8a2eaa11dc63b9b9f to your computer and use it in GitHub Desktop.
Save gragera/fab8a2eaa11dc63b9b9f to your computer and use it in GitHub Desktop.
Using swift generics for easier storyboard ViewController instantiation
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")
@drodriguez
Copy link

func instantiate<T>(identifier: String) -> T {
  return instantiateViewControllerWithIdentifier(identifier) as! T
}

allows me to do:

let vc: MyViewController = storyboard.instantiate("MyViewControllerIdentifier")

But I actually think that:

let vc = storyboard.instantiate<MyViewController>("MyViewControllerIdentifier")

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.

@gragera
Copy link
Author

gragera commented Jun 2, 2015

Updated, thanks for the tip!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment