Simpler iOS Storyboard Instantiation

Eddie
codeburst
Published in
2 min readJun 19, 2017

--

Programmatic Storyboard View Controller Instantiation using Swift Protocols & Generics

I was recently rewriting my weather app (for the third time) and I decided to fully embrace storyboards and Interface Builder. Why? 🤔 Well, the first version of my app had no storyboards, the second used ASDK, so it felt right that the third use storyboards.

As I was writing the typical UITableViewDataSource cellForRowAtIndexPath boilerplate, I stumbled across this article:

I used the protocol extension + generics technique to elegantly return a typed subclass UITableViewCell without repeating code or casting in my table view data sources👌

But after typing out the same code twice to instantiate two different view controllers in two different storyboards I had a 💡 moment. I could use the same technique to return typed subclass UIViewControllers! 🙌

Here it is:

Drop this file into your code and DRY up your code.

Let’s break things down a bit:

To instantiate a UIStoryboard we need to know the name of the storyboard file, so we make anything that’s Storyboardable provide a storyboardName.

Then, we use a protocol extension to implement storyboardName to be the name of the UIViewController, making sure to constrain ourselves to only UIViewController. So it's a requirement that the storyboard file and the UIViewController subclass are named the same!

In the same protocol extension the magic happens 🎩✨🐇. We create the UIStoryboard, instantiate the initial view controller (Don’t forget to set “Is Initial View Controller” in your storyboard!), and using generics we’re able to cast the UIViewController to a custom subclass and return it.

This line of code allows you to use this technique on any UIViewController subclass you create.

Now, your view controller instantiation from storyboards is as simple as:

Which is more idiomatic than:

Questions and feedback welcome!

~Eddie.

Update

I received some great feedback from the community over at ios-developers.io. Here’s version two of Storyboardable:

Now the object returned from the storyboardViewController method is the expected type. You don’t need to specify the object type when declaring your variables anymore:

--

--