Keeping your UIViewController clean in Swift

One of my biggest interest when it comes to coding is code quality and code structure. Code often grows complex over time and it can be hard not introducing bugs and making code that is difficult to refactor, maintain and read. A common issue I think many iOS developers have experienced is related to the UIViewController class. This class is very central when it comes to native iOS development. It handles the logic behind a single screen or parts of a screen displayed to the user. Also Apple does not provide any good guidance to avoid this.

I have based this post around the suggestions from this other blog post where the author discusses common bad practices with over-using the UIViewController:

He lists a few common uses for the UIViewController which could be considered bad.

  1. View setup and custom layout code
  2. Core data code
  3. Delegate for everything
  4. Accessing global states (singletons)
  5. Navigation logic

I mostly agree with the author and want my classes and methods to be as small as possible as well as only have one single responsibility. iOS ViewControllers tend to become way to large and like the author says, if you do not put in effort to restructure and refactor your ViewControllers, your app will so only consist of enormous ViewControllers.

MVC Twitter link


A good starting point for anyone who wants smalled ViewControllers is to install the XCode Alcatraz plugin Luft which warns you (coloring the line number view red) when your ViewControllers get to big. I like the idea!

Continue reading