View Controller Factory in Swift

Decoupling view controller creation.

Srikanth Sombhatla 
2 min readAug 25, 2018

Creating view controllers is an essential task in iOS programming. However, it is very easy to get tangled in an unwanted code coupling without ever noticing it. Lets see the problem in detail and learn how to apply a design pattern to solve it.

I will take a simple hypothetical user on-boarding flow to put across a scenario.

  1. Users starts with a Landing Page from where the navigation is branched to Signup or Login.
  2. Users can navigate to Login from Signup, in case they recall they did have an account.
  3. Users can navigate to Forget Password from Login.
  4. On successful Signup/Login Users can navigate to Home screen.

A typical view controller would look like this

The above code has few problems

  1. Firstly, each view controller knows about the other view controller. Thats just not good. What if a storyboard name or storyboard id is changed? This ripple effect is felt across all the view controllers that have this unwanted coupling.
  2. We cannot test.

Lets solve this by applying a creation pattern called Factory. By doing so we want to

  1. Create view controllers without knowing the details.
  2. Provide a mechanism to predictably test.

Here we create enums for all supported view controllers. Each enum provides a storyboard representation from which we can create a view controller.

Adding new view controllers is easy as adding another enum case. Moreover when we look at the enum we get a bird’s eye view of all view controllers used in the app.

And we use it as

But what if …

We want to configure a view controller before pushing it ? How can we do that cleanly without adding unwanted dependencies? Thats the next topic in the trilogy.

Keep calm. Keep coding.

--

--

Srikanth Sombhatla 

iOS and Qt Developer. Strong believer and advocate of mobile first strategy. Photographer. Blogger.