A Very Narrow Usage of Storyboards

Lately I’ve been struggling to balance the pros and cons of various view controller initialization techniques. There are three, none of which are perfect:

Lately, the projects I’ve been working on have had pretty heavy AutoLayout requirements. As such, it’s been easiest to build the user interface logic using a Storyboard. But the Storyboard approach makes it really hard to pass in dependencies in a simple, reliable fashion.

Until Apple provides a better solution, my current strategy is to provide a static factory method that takes as arguments all the dependencies that need to be passed in:

static func newFromStoryboard(foo: FooDependency, bar: BarDependency) -> MyViewController

In addition, I make the relevant instance variables private, so that they can only be set from inside the file:

private var foo: FooDependency!
private var bar: BarDependency!

The factory method instantiates the view controller from the correct storyboard, and then sets all the dependencies. I only use one view controller per storyboard, and never use segues.

This is not the most elegant approach I can imagine, but I believe it’s the least inelegant approach made possible within the current state of the UIKit framework and Swift.

|  27 Apr 2016