As a lead on a UIKit app, would you let view controllers push their own next screen or make coordinators own each flow, and what does the coordinator rule cost?
answer
- who picks the next screen
- an object that owns the navigation controller
- a flow, not a screen
- Back and the edge swipe skip it
- one weak delegate on the navigation controller
basics
~20 sSelf-routing screens are simplest for small apps but hard-wire each flow into its view controllers. Coordinators own the UINavigationController and choose the next screen, making flows reusable, but must track Back pops and their own lifetime.
solid answer
~50 sWhen a view controller builds and pushes its successor, the flow lives in the screens: easy to read, hard to reuse, since checkout opened from the basket and from a reorder button needs two copies of the sequence. A **coordinator** is a plain object that owns a `UINavigationController`, creates the screens and decides what comes next; screens report intent through closures or delegates. That buys reuse, testable flows and screens that know nothing about each other. The cost is UIKit-specific: the system Back button and the edge swipe pop without asking the coordinator, so it must watch `navigationController(_:didShow:animated:)` or the screen's `isMovingFromParent` to learn that a flow ended; UIKit holds no reference that keeps a coordinator alive, so parents must hold children and release them; and `delegate` is one weak property shared with custom animators. My rule: a coordinator per multi-screen flow, not per screen.
code
swift · 35 linesimport UIKit
final class AddressViewController: UIViewController {
var onContinue: (() -> Void)?
}
@MainActor
final class CheckoutCoordinator: NSObject, UINavigationControllerDelegate {
private let navigationController: UINavigationController
private weak var firstScreen: UIViewController?
var onFinish: (() -> Void)? // the parent coordinator releases this one here
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func start() {
navigationController.delegate = self
let address = AddressViewController()
address.onContinue = { [weak self] in self?.showPayment() }
firstScreen = address
navigationController.pushViewController(address, animated: true)
}
private func showPayment() { /* push the payment screen */ }
// The system Back button and the edge swipe pop without asking the coordinator.
func navigationController(_ navigationController: UINavigationController,
didShow viewController: UIViewController, animated: Bool) {
let stillInFlow = navigationController.viewControllers.contains { $0 === firstScreen }
guard !stillInFlow else { return }
onFinish?() // the user backed out of checkout entirely
onFinish = nil
}
}go deeper
Recall what a coordinator is: an ordinary object that creates screens and pushes them, while screens only report what the user did.
Explain why Back and the edge swipe bypass the coordinator and how navigationController(_:didShow:animated:) or isMovingFromParent reveals the pop.
Manage child coordinator lifetimes, share the single navigation delegate with custom animators, and route presentations through the coordinator so swipe dismissals are reported.
Decide the scope of the rule: coordinators for multi-screen flows only, a single owner per navigation controller, and when a small app is better off with screens routing themselves.
## Two ways to pick the next screen Every UIKit app answers one question on every tap: **who creates the next view controller and pushes or presents it?** | Approach | Where the flow lives | Gains | Costs | |---|---|---|---| | screens route themselves | inside each view controller's action methods | least code, easy to follow in a small app | screens import each other; a flow reused from two entry points is written twice; flows are hard to test without UIKit | | coordinators own flows | in a separate object per flow | screens are independent; a flow is reused and tested as one unit | more types; Back handling and lifetimes become your job | A **coordinator** is not a UIKit class. It is a plain object, usually main-actor isolated, that holds a `UINavigationController` (or presents on one), creates each screen, wires each screen's output closures, and decides the next step. In a food-delivery app, a `CheckoutCoordinator` owns address, payment and confirmation; the basket and a "reorder" button both start it. ## What UIKit makes you handle ### Pops the coordinator never sees The coordinator pushes screens, but the user pops them with the **Back button**, the **leading-edge swipe** (`interactivePopGestureRecognizer`), or the **long-press list** on Back. None of these ask the coordinator. A coordinator that only tracks its own calls keeps believing checkout is open. Two ways to notice: - Make the coordinator the navigation controller's delegate and, in `navigationController(_:didShow:animated:)`, check whether its first screen is still in `viewControllers`. - Or let the first screen report it from `viewDidDisappear(_:)` when `isMovingFromParent` is true, which the header suggests for telling a pop from other disappearances. ### Lifetime UIKit keeps view controllers alive through the stack, but **UIKit holds no reference that keeps a coordinator alive**: `UINavigationController.delegate` is `weak`, and screens should capture their coordinator weakly in their closures. A parent coordinator keeps an array of child coordinators, adds the child when the flow starts, and removes it when the child reports it finished, whether by completing or by the user backing out. Missing that removal leaks the coordinator and its closures; removing it too early leaves screens whose callbacks go nowhere. ### One delegate slot `navigationController.delegate` is a **single** property. If the coordinator takes it to watch pops, it also owns `navigationController(_:animationControllerFor:from:to:)`, so the custom dish-photo animator must be returned through the coordinator or a composite delegate. Two features that each assign the delegate silently break each other. ## Setting the team rule 1. **Coordinator per flow, not per screen.** A two-screen settings drill doesn't need one; checkout, onboarding and sign-in do. 2. **Screens never push the next feature.** They expose output closures such as `onContinue` or `onCancel`, and the coordinator reacts. 3. **One owner of the navigation delegate** per navigation controller, documented in the code review checklist. 4. **Every child coordinator reports finish** on every exit, including Back, and the parent releases it. 5. **Presentations go through the coordinator too**, so a sheet dismissed by a swipe is reported like a pop. ## Testing what the rule buys The payoff should be visible in tests, or the rule is ceremony: - A coordinator is tested by giving it a real `UINavigationController`, calling `start()`, and asserting on `viewControllers` after each output closure fires. - A screen is tested alone by triggering its actions and checking which closure was called, with no navigation controller involved. - A back-out is tested by popping the coordinator's first screen and checking that the finish closure ran once. If the team writes none of these tests, most of the gain left is readability, and the cost column of the table weighs more. ## When not to adopt it A small app with one main flow, a short-lived prototype, or a team that leans on storyboard segues pays the coordinator overhead without enough reuse to repay it. Segues route inside the storyboard, so mixing them with coordinators gives two sources of truth; pick one per flow. What remains in every case is the decision itself: write down who is allowed to touch a navigation controller's stack. How screens are wired across feature modules, and how an incoming link builds a stack, are design questions for the system design material on navigation; the rule above is about the UIKit objects.
- How does a coordinator coexist with the custom dish-photo push animator?UINavigationController has one weak delegate, so pick a single owner. The coordinator becomes the delegate and returns the animator from navigationController(_:animationControllerFor:from:to:) for the push it animates, or it forwards that call to a small animator provider. Never let a feature assign the delegate behind the coordinator's back, or one of the two silently stops working.
- How should a parent coordinator release a child whose flow the user abandoned with Back?The child detects the exit, for example in navigationController(_:didShow:animated:) when its first screen is no longer in viewControllers, and calls its finish closure once. The parent removes the child from its array of children and, if the child had taken the navigation controller's delegate, restores its own. With its screens capturing it weakly, nothing else retains the child, so it deallocates with its closures.
A coordinator is a stage manager: actors only say "my scene is done", and the stage manager decides which scene comes next. But audience members can walk out through a side door (the Back button) without telling anyone, so the stage manager has to watch the door too.
- Assumes every pop goes through the coordinator, ignoring Back and the edge swipe.
- Thinks the navigation controller retains its delegate, keeping the coordinator alive.
- Creates a coordinator for every screen, adding types without owning a flow.
- Lets two features each assign navigationController.delegate independently.