SwiftUI Coordinators/Routers, a bit of a brain dump [1/n]
I’be found the flexibility of the Coordinator pattern with programmatic UIKit (MVP/MVVM) to be extremely worthwhile. Pulling the logic of navigation into a separate place, away from the VCs is awesome
In SwiftUI, passing bindings through, for controlling things like a sheet displaying, and then toggling them at any exit point out of that modal view, feels clunky to me.
I’m using MVVM, so, my views have view models. Sending global dependencies into those VMs, from the view layer, feels odd. E.G pulling values out of SwiftUI’s environment, and then instantiating a VM the view observes. The view is then doing too much non view work
So, I thought, what might a coordinator or “router” (heck, perhaps we need a new word here) look like?

Imagine our view talks to this router via a kind of delegate pattern. So;

protocol ViewRouter: ObservableObject {
func dismissMe()
}
In the view, we hold reference to this via @ObservedObject, and then buttons etc can talk to these functions. The router implements them, and decides what to do
The router also has to produce the first view and gives this to the app at start up.

It can do this via a @ViewBuilder function that decides what view to return based on some state.

Via the link to views described above, the router can then change that state
The router can also house dependencies, and inject them into view models, before giving them to the views it creates in it’s @ViewBuilder functions
And bingo, I’ve an approach where my views only ever represent state from their VM’s, and only ever trigger changes in flow via their router. No playing pass the parcel with bindings
This thread’s not done, but I’m done for now. I’ll add more over time
You can follow @davidgarywood.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: