SwiftPumpkin

2 of 20 · UI patterns

MVVM (+ Router)

MVVM with a Router: the ViewModel owns presentation state and logic, the Router owns navigation, and the view controller just binds and forwards.

How it's wired

User actionsStateCallsDataRouteView + VCLifecycle, bindingViewModelPresentation logicRouterNavigationModelDomain + services
calls or tellsreports backMVVM with a Router (MVVM-R): the view controller binds and forwards, the ViewModel decides, the Router navigates. Exact router ownership varies by codebase.
  • ViewModel: state and decisions.
  • Router: navigation. View controller: binding only.
PartOwnsLooks like
Entity / ModelDomain objects, data and domain behaviorStructs, domain services
ViewModelPresentation logic, state transformations, user actions, coordination with domain services@MainActor class, no UIKit
ViewLayout, rendering and UI interactionsUIView subclasses, SwiftUI View
ViewControllerUIKit lifecycle, bindings, event forwarding and view compositionUIViewController
RouterNavigation, screen construction and transitionsHolds weak view controller

MVVM-R in Swift

One save-a-note screen. Read it top to bottom: the arrows point inward.

Contracts

The ViewModel depends on these, never on concrete types.

protocol NoteStoring: Sendable {  // crosses actors, so Sendable
  func save(_ note: ThankYouNote) async throws
}

@MainActor
protocol NoteRouting {
  func showSaved()
}

ViewModel

State and decisions. No UIKit import.

@MainActor @Observable
final class NoteViewModel {
  var recipient = ""
  var message = ""
  private(set) var error: String?
  private(set) var isSaving = false

  var canSave: Bool {
    !isSaving && NoteRules.canSave(recipient: recipient, message: message)
  }

  private let notes: any NoteStoring
  private let router: any NoteRouting

  init(notes: any NoteStoring, router: any NoteRouting) {
    self.notes = notes
    self.router = router
  }

  func save() async {
    guard !isSaving else { return }  // a double tap must not save twice
    error = nil  // clear any stale error from a prior attempt
    isSaving = true
    defer { isSaving = false }
    do {
      try await notes.save(ThankYouNote(recipient: recipient, message: message))
      router.showSaved()  // navigation is the router's job
    } catch {
      self.error = "Couldn't save. Try again."
    }
  }
}

Router

If Screen A pushes Screen B directly, Screen A must carry Screen B's dependencies, can't be reused in another flow without flags, and can't be navigation-tested without UIKit. A Router keeps screens flow-agnostic.

@MainActor
final class NoteRouter: NoteRouting {
  weak var navigation: UINavigationController?

  func showSaved() {
    navigation?.popViewController(animated: true)
  }
}

View controller (UIKit, iOS 17–18)

UIKit can observe @Observable directly via withObservationTracking—no Combine or closure boilerplate needed.

final class NoteViewController: UIViewController {
  private let viewModel: NoteViewModel

  override func viewDidLoad() {
    super.viewDidLoad()
    render()
  }

  // Re-runs when any @Observable property read inside changes.
  // onChange fires on willSet; gate re-renders on view visibility.
  private func render() {
    withObservationTracking {
      saveButton.isEnabled = viewModel.canSave
      errorLabel.text = viewModel.error
    } onChange: { [weak self] in
      Task { @MainActor in
        guard let self, self.viewIfLoaded?.window != nil else { return }
        self.render()
      }
    }
  }

  @objc private func saveTapped() {
    Task { await viewModel.save() }
  }
}

View controller (UIKit, iOS 26+)

On iOS 26, UIKit tracks @Observable reads inside updateProperties() automatically—just read the properties and UIKit re-invokes it on change.

final class ModernNoteViewController: UIViewController {
  private let viewModel: NoteViewModel

  override func updateProperties() {
    super.updateProperties()
    // UIKit records reads of canSave and error and schedules
    // updateProperties() again whenever either changes.
    saveButton.isEnabled = viewModel.canSave
    errorLabel.text = viewModel.error
  }

  @objc private func saveTapped() {
    Task { await viewModel.save() }
  }
}

Assembly and test

One place wires concrete types; the test needs no UIKit.

@MainActor
func makeNoteScreen(notes: any NoteStoring, nav: UINavigationController) -> UIViewController {
  let router = NoteRouter()
  router.navigation = nav
  return NoteViewController(viewModel: NoteViewModel(notes: notes, router: router))
}

@Test @MainActor
func savingRoutesBack() async {
  let router = RouterSpy()
  let viewModel = NoteViewModel(notes: InMemoryNotes(), router: router)
  viewModel.recipient = "Mom"
  viewModel.message = "Thanks for dinner"
  await viewModel.save()
  #expect(router.didShowSaved)
}

Trade-offs, and what experts watch for

  • +Presentation logic is testable without UIKit.
  • +The view renders one state instead of receiving commands like setSaveEnabled (the older MVP style), so rotation, restoration and cell reuse never mean replaying calls. Tests assert on state instead of recording calls.
  • +Screens stay reusable across flows because they report intent instead of constructing and pushing the next screen.
  • -A ViewModel that only forwards calls to a service is indirection without real separation, so thin screens stay MVC.
  • -One more object per flow, and its lifetime to manage.
  • Massive ViewModel symptoms: tests needing five or more mocks (DB, network, analytics, flags), merge conflicts between unrelated edits, or backend rule changes forcing UI re-tests. It matters only on actively changing screens; leave a stable ViewModel alone.
  • An interactor (also called a use case or domain service) is a plain, UI-free type that owns business rules and data orchestration, such as eligibility checks or multi-step saves. The ViewModel calls it and maps results to UI state.
  • How @Observable works: it is a Swift compiler macro that tracks reads and writes on stored vars at runtime. Only properties whose getters actually execute during a render trigger updates; mark internal mutable state (like a Task handle) @ObservationIgnored.
  • UIKit bindings: view controllers observe @Observable ViewModels with withObservationTracking on iOS 17–18, or automatically inside updateProperties() on iOS 26 (both shown below), replacing Combine and hand-rolled closures.
  • Keep ViewModels @MainActor and their outputs value types. Async work lives in services; the ViewModel awaits and updates state.

When I'd use it

Interactive UIKit screens with async state or validation (forms, feeds, search, detail views)MVVM with a Router: keeps loading, errors and enable/disable rules testable without UIKit.
Complex flows where business rules and UI evolve independently (checkout, pricing, contact picker)Pull out an Interactor or UseCase, or use VIPER for that flow.
Multi-step flows with branching or deep links (onboarding, payment wizard)Add a Coordinator above the screens to own flow order and back-stack restoration.
Thin static screens with no async or derived state (About, Licenses, simple Settings)Plain MVC: a ViewModel here would only forward properties one-to-one.

Expert notes

  • MVC → MVVM-R → VIPER, each step only where complexity earns it.

Check yourself

Answer out loud before you reveal. Recall is what makes it stick.

30-second answer

Explain MVVM (+ Router) in 30 seconds.

iOS codingAsked directly

MVVM vs MVC in UIKit: what exactly moves into the view model, and what does that buy you?

iOS codingAsked indirectly

The model changes from network updates while the screen is visible. How does your view model keep the view in sync?

System designAsked indirectly

Your team is debating MVC versus MVVM for a new app. What questions settle it?

System designAsked indirectly

Your team wants MVVM but refuses to adopt a reactive framework. Is that viable?

System designAsked indirectly

A year after moving to MVVM, view models are 800 lines. What went wrong?

System designAsked indirectly

Does AI-assisted development change how you'd architect an iOS app?

Read it in the app's source

Done with MVVM (+ Router)? Mark it complete. Nailing its cards builds this pumpkin, row by row.