4 of 20 · UI patterns
Coordinator / Routing
A coordinator is an object that owns navigation for a flow. Screens report what happened ("user picked a pumpkin") and the coordinator decides what comes next, so view controllers never create or push each other.
How it's wired
- A coordinator owns a UINavigationController and the flow.
- Each screen exposes callbacks like onNext instead of pushing other screens.
| Part | Owns | Looks like |
|---|---|---|
| Coordinator | Create screens, decide flow, own navigation | Class holding UINavigationController |
| Screen | Display and report intent | UIViewController with closures |
| Child coordinators | Sub-flows with their own lifetime | Array in parent |
Swift example: why navigation leaves the ViewModel, plus UIKit pitfalls
First, see why a ViewModel shouldn't push the next screen; then see the two UIKit coordinator bugs that ship most often (back-swipe leaks and modal collisions).
Before vs. after: decoupling a reused screen from its flow
With navigation in the ViewModel, reusing ContactPicker forces EntryPoint branching and drags downstream dependencies (MessageStore, GroupService) into a picker that doesn't use them.
// ❌ Navigation inside ViewModel: coupled to every caller and its dependencies.
@MainActor
final class CoupledContactPickerVM {
enum EntryPoint { case newChat, addToGroup(groupID: String) }
private let entryPoint: EntryPoint
private let messages: MessageStore // only needed to build ChatVC!
private let groups: GroupService // only needed to add to a group!
func didSelect(_ contact: Contact) {
switch entryPoint {
case .newChat:
nav.pushViewController(ChatVC(contact: contact, messages: messages), animated: true)
case .addToGroup(let id):
groups.add(contact, to: id)
nav.dismiss(animated: true)
}
}
}
// ✅ Report intent only: the owning coordinator decides what happens next.
@MainActor
final class ContactPickerVM {
private let onSelect: (Contact) -> Void
init(onSelect: @escaping (Contact) -> Void) { self.onSelect = onSelect }
func didSelect(_ contact: Contact) { onSelect(contact) }
}
// NewChatCoordinator passes: { self.showChat(with: $0) }
// AddToGroupCoordinator passes: { self.addMember($0) }Child lifecycle + safe modal presentation
Observe UINavigationControllerDelegate so a user back-swipe releases the child coordinator, and dismiss or queue when a modal is already presented.
@MainActor
final class CheckoutCoordinator: NSObject, UINavigationControllerDelegate {
private let navigation: UINavigationController
private var children: [ObjectIdentifier: AnyObject] = [:]
private var onFinish: (() -> Void)?
init(navigation: UINavigationController, onFinish: @escaping () -> Void) {
self.navigation = navigation
self.onFinish = onFinish
super.init()
navigation.delegate = self
}
func presentSheet(_ sheet: UIViewController) {
// UIKit silently drops present(_:) if another modal is already active.
if let active = navigation.presentedViewController {
active.dismiss(animated: false) { [weak self] in
self?.navigation.present(sheet, animated: true)
}
} else {
navigation.present(sheet, animated: true)
}
}
func navigationController(
_ nav: UINavigationController,
didShow viewController: UIViewController,
animated: Bool
) {
guard let from = nav.transitionCoordinator?.viewController(forKey: .from),
!nav.viewControllers.contains(from)
else { return }
// Back-swipe popped a child's root VC: release its coordinator so it doesn't leak.
children.removeValue(forKey: ObjectIdentifier(from))
}
}In production, a parent coordinator typically multiplexes UINavigationControllerDelegate across all active children.
Why pull navigation out, and what makes coordinators hard
- Why not navigate from the ViewModel? First, transitive dependencies: if FeedViewModel builds ProfileScreen, which builds ChatScreen, FeedViewModel's init must carry ChatScreen's dependencies even though it never uses them.
- Second, flow coupling and lifetime: reusing a ContactPicker from New Chat versus Add to Group forces EntryPoint switches inside the ViewModel, and multi-step flow state (checkout, onboarding) outlives any single screen.
- Lifetime. A parent must retain its child coordinators and release them when a child finishes. Back-swipe and interactive modal dismissal bypass your finish callback, so you also need UINavigationControllerDelegate or the presentation controller's delegate, or the child leaks.
- Single-delegate contention. UINavigationController has only one delegate, so a child setting navigation.delegate = self silently overwrites its parent's delegate. Route callbacks through one root nav delegate or multiplexer instead.
- Modal and transition collisions. UIKit silently drops present(_:) when another modal is active—including sheets pushed by third-party SDKs or first-party libraries without notifying your coordinator—and pushing mid-animation corrupts the stack. Check the live presentation hierarchy before presenting.
- Flow vs. execution. Coordinators or stateless Routers decide what comes next; in large UIKit apps, put a central Presentation Queue underneath to serialize animations, catch third-party SDK modals, and enforce priority and staleness so an expired promo doesn't appear after checkout.
- Deep links. Navigation becomes "set state, then start": build any valid stack from a route, and handle links arriving while logged out (deferred until post-auth), over an active modal, or requiring an async lookup first.
- In SwiftUI, NavigationStack(path:) makes navigation a value. The coordinator becomes an @Observable router that owns the path, which is easy to unit test and restore.
When I'd use a coordinator
| Multi-step flows | Onboarding, checkout, this thank-you wizard. |
|---|---|
| Screens reused from several places | A coordinator per flow, the screen unchanged. |
| One list and one detail | Skip it: child-lifecycle bookkeeping only pays back once flows branch, reuse screens, or restore deep links. |
Compared
Segues vs coordinator vs SwiftUI path
| Segues | Coordinator | Path | |
|---|---|---|---|
| Who picks the next screen | Source VC | Coordinator | Code mutating path |
| Reuse a screen in another flow | Hard | Easy | Easy |
| Deep links | Manual chains | Build stack from route | Assign the path |
| Testing navigation | UI tests | Unit tests | Unit tests |
Expert notes
- A good interview signal: a screen should be usable from two flows without edits. If it can't be, something is pushing it from the wrong place.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Coordinator / Routing in 30 seconds.
- A coordinator owns navigation for a flow.
- Screens report intent, like “user picked a pumpkin”, and the coordinator decides what's next, builds it and pushes it.
- Because screens never know what follows them, one screen can serve two flows and a deep link becomes building a stack.
- I add one when a screen is reused across flows or navigation depends on state.
- The cost is lifetime management: parents retain child coordinators and must release them, including on back-swipe.
What problem does the Coordinator pattern solve, and how do child coordinators stay alive and get cleaned up?
- It stops view controllers from building and presenting the next screen, which welds each one to a single flow.
- A coordinator is a plain object that owns the flow instead.
- Parents keep children in
var childCoordinators: [Coordinator]so they stay alive, and remove them when the child reports it's done. - Forget that removal and you leak whole flows.
- I'd add coordinators when navigation is reused or conditional; for a linear two-screen flow, a closure from the parent is cheaper.
This detail screen must open from two different flows. How do you avoid it knowing where it came from?
- Have the screen report intent instead of navigating.
- A view controller should manage either the sequence of screens or its own UI, never both.
- The list turns the row into a model and calls
delegate?.didSelect(item). - A parent flow controller that owns the navigation stack decides what comes next.
- Either flow can then host the same detail screen unchanged.
An edit-profile screen needs to save via an API call. Does the POST belong in the view controller?
- No, and not in the coordinator either.
- The view controller reports “save tapped” with the edited values.
- The view model or an interactor performs the save through an injected API client.
- The coordinator only decides what happens next: dismiss, or show login if the session expired.
- I keep “who changes data” apart from “who navigates”, because a coordinator that also saves can't be tested without a network and grows with every feature.
Read it in the app's source
Done with Coordinator / Routing? Mark it complete. Nailing its cards builds this pumpkin, row by row.