iOS: View Controller Data Injection with Storyboards and Segues in Swift

Since I openly declared my love for Storyboards & Nibs earlier this week, I’ve gotten a lot of questions on how I deal with injecting dependencies between View Controllers without using a custom initializer. So I’ll share that now.

But first, I’d like to say that my solution is not perfect, and it’s a workaround around how UIViewController works. Hopefully Apple will provide a more flexible and Swifty UIKit API (with protocols instead of subclassing!) down the line that will allow the very common case of dependency injection!

Second, the reason I’m a against messing with the initializers is because we have to subclass our UIViewControllers from UIKit. There are already several initializers there and we have to call super on them because UIKit is doing work behind the scenes (which we cannot see the source code of):

Sure, it’s been the same for while and will likely not change, but since I don’t have control or visibility into UIKit, I prefer to work with how it’s meant to be used rather than against it by creating my own clever initializers!

So the way I prefer to handle this issue is by using Implicitly Unwrapped Optionals 😱😱😱

I’ll use this project as an example. The detail view controller – the one that depends on a value from the previous view controller, has an implicitly unwrapped optional variable for the value that it absolutely needs at the time that it’s initialized or loaded:

In this case, if mainText is NOT assigned in prepareForSegue, this view controller will immediately crash 💥 This will make it super easy for the developer writing this code to immediately address the problem and assign the dependency:

The key is to make sure that the implicitly unused optional is assigned or used during the detail view controller’s initialization / view loading cycle! If it’s used later on, the view controller will not crash when the implicitly unwrapped optional is passed in as @justMaku points out:

As I mentioned, this is not the perfect solution, just one I’m ok living with compared to alternatives giving the constraints of UIKit.

You can view the full sample project on Github here.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.