The education of Paul Weichhart

Write like nobody is reading

Coordinators in SwiftUI

Similar to Massive View Controllers, SwiftUI Views can grow exponentially & have way too much responsibility. Moving any functionality to a separate Layer is a welcoming choice.

The Coordinator Design Pattern aims to solve one part of the problem by moving the presentation related code to a distinct class. It is also one of the most underrated Patterns when it comes to developing iOS Apps. Soroush Khanlou wrote an excellent article why you should introduce Coordinators in your Application. I tried to map his recommendations in the following example code.

I did some experiments and looked into a couple of different approaches — in the end I chose the following setup:

  • The Coordinator acts as a Factory for creating the Views
  • I used an enum for the different destinations (similar to the recommendation in Soroush’s article)
  • The switch is implemented inside a View in order to avoid having AnyView & therefore a decreased Performance
  • The View is an inline struct and not exposing any API
  • The Coordinator is an @EnvironmentObject added to the root View to give Subviews access to it

The inline struct can also be replaced with a dedicated func for each Destination that returns the View.

In the View the Coordinator can be called as follows:

I also created a Repository on Github to make the code examples more readable. Something you would like to know or wanted to add? Drop me 280 characters on twitter @paulweichhart