Type-safe method to instantiate a viewcontroller from storyboard in Swift

The Problem

I really like storyboards, i like to draw my ui flow in one place without need of creating new .xib files for each controller. But there is a thing i miss from olds xibs, with xibs i can instantiate viewcontrollers in a single line of code:

With storyboards, this is also possible but require a little more effort:

I don’t like this way, you have to cast always to the right class, identifiers are hard-coded strings, you have to add them in Interface Builder and then you have to remember and copy the strings everywhere in your code. Misspelling are behind the corner!
And of course if you decide to change the name of the identifier, you need to change it in every place it was hard-coded. A solution to hard-coding identifiers could be the use of enums:

But that not solve type-safety, we still need cast to right type.

The Solution

I think the final use is very elegant and easy to use, you will have to design your viewcontroller in storyboard, assign a class, and use the same class name as identifier in Interface Builder. After few search, i wrote these lines of code:

First, i create a protocol called StoryboardInstantiable. Class variables or class methods are not allowed in protocols, use static instead.

Now we can extend UIViewController class to conform StoryboardInstantiable protocol. The idea is to use the view controller’s class name as identifier, so we will write it only once in Interface Builder.

The next time you will need to instantiate manually your view controller, just use

One more tip

If you are tired of instantiate everytime the main Storyboard, this little method, return automatically the storyboard marked as main in the project settings

So the final code to instantiate manually a viewcontroller become

You can view and download the full sample project on Github here.

Un pensiero su “Type-safe method to instantiate a viewcontroller from storyboard in Swift

  1. leonardo lombardi

    Nice idea, but you still need to match the view controller identifier with the class name.

    Would be nice if we could just get a reference programatically to all view controllers that conform / implement a protocol. Then you would just need to make your classes implement it.


Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *