SwiftPumpkin

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

Creates, pushesonNextCreates, pushesonFinishCoordinatorOwns the flowScreen AReports intentScreen BReports intent
calls or tellsreports backScreens never create or push each other. The coordinator decides what comes next.
  • A coordinator owns a UINavigationController and the flow.
  • Each screen exposes callbacks like onNext instead of pushing other screens.
PartOwnsLooks like
CoordinatorCreate screens, decide flow, own navigationClass holding UINavigationController
ScreenDisplay and report intentUIViewController with closures
Child coordinatorsSub-flows with their own lifetimeArray 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 flowsOnboarding, checkout, this thank-you wizard.
Screens reused from several placesA coordinator per flow, the screen unchanged.
One list and one detailSkip it: child-lifecycle bookkeeping only pays back once flows branch, reuse screens, or restore deep links.

Compared

Segues vs coordinator vs SwiftUI path

SeguesCoordinatorPath
Who picks the next screenSource VCCoordinatorCode mutating path
Reuse a screen in another flowHardEasyEasy
Deep linksManual chainsBuild stack from routeAssign the path
Testing navigationUI testsUnit testsUnit 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.

30-second answer

Explain Coordinator / Routing in 30 seconds.

iOS codingAsked directly

What problem does the Coordinator pattern solve, and how do child coordinators stay alive and get cleaned up?

iOS codingAsked indirectly

This detail screen must open from two different flows. How do you avoid it knowing where it came from?

System designAsked indirectly

An edit-profile screen needs to save via an API call. Does the POST belong in the view controller?

Read it in the app's source

Done with Coordinator / Routing? Mark it complete. Nailing its cards builds this pumpkin, row by row.