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

Last week, I wrote about how I do View Controller Data Injection with Storyboards and Segues in Swift

TL;DR – It’s not an ideal solution, but I use Implicitly Unwrapped Optionals (IUOs) that I make sure to use in viewDidLoad (or earlier in the ViewController lifecycle) so there is an explicit 💥 if it’s not set.

Since then, many have chimed in with solution they use, but honestly, they all seem super complicated, ugly, and unreadable. Many mentioned this is why they don’t use storyboards, etc. So I was ok with my not-so-great, but simple, solution.

However, yesterday I read a comment by @cduhn on my I 💖 Storyboards & Nibs blog post that triggered an idea for a slightly better solution.

Here is the comment:

“I look forward to using the implicitly unwrapped var trick when I migrate to Swift. For now, here’s the idiom I like to use for dependency injection with storyboards in Objective C:

1. Each view controller has a public method starting with setDependencies like this:

2. Each view controller has a private method called -assertDependencies, which I call at the top of viewDidLoad.

3. Now simply call setDependencies in prepareForSegue:

One of the things I like about this idiom is that all the dependencies of the class are bundled up in a single method signature, just like a good initializer. If you forget to inject a dependency, you find out about it at compile time.

So here is a more Swifty version of this solution that I’m playing with:

First, create an Injectable Protocol:

Now, my Implicitly Unwrapped Optional dependency can be private:

Now, in prepareForSegue, we can use the inject method:

The thing I really like about this is that it standardizes the inject method for all ViewControllers that need dependency injection. It’s easy to just start typing “inject” in prepareForSegue to see if something needs to be injected vs trying to remember the exact thing that needs to be set!

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