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.
Navigating in SwiftUI
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
enumfor the different destinations (similar to the recommendation in Soroush’s article) - The switch is implemented inside a
Viewin order to avoid havingAnyView& therefore a decreased Performance - The
Viewis an inlinestructand not exposing any API - The Coordinator is an
@EnvironmentObjectadded to the rootViewto 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