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
- ViewModel: state and decisions.
- Router: navigation. View controller: binding only.
| Part | Owns | Looks like |
|---|---|---|
| Entity / Model | Domain objects, data and domain behavior | Structs, domain services |
| ViewModel | Presentation logic, state transformations, user actions, coordination with domain services | @MainActor class, no UIKit |
| View | Layout, rendering and UI interactions | UIView subclasses, SwiftUI View |
| ViewController | UIKit lifecycle, bindings, event forwarding and view composition | UIViewController |
| Router | Navigation, screen construction and transitions | Holds 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
@Observableworks: it is a Swift compiler macro that tracks reads and writes on storedvars at runtime. Only properties whose getters actually execute during a render trigger updates; mark internal mutable state (like aTaskhandle)@ObservationIgnored. - UIKit bindings: view controllers observe
@ObservableViewModels withwithObservationTrackingon iOS 17–18, or automatically insideupdateProperties()on iOS 26 (both shown below), replacing Combine and hand-rolled closures. - Keep ViewModels
@MainActorand 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.
Explain MVVM (+ Router) in 30 seconds.
- MVVM with a Router splits a screen three ways.
- The ViewModel holds presentation state and decisions without importing UIKit, the Router owns navigation and builds the next screen, and the view only renders and forwards intent.
- That makes presentation logic testable without a view and lets flows change without touching screens.
- It's my production default once a screen has collections or several async sources.
- The risk is a ViewModel that only forwards calls to a service, which adds indirection without separation.
MVVM vs MVC in UIKit: what exactly moves into the view model, and what does that buy you?
- Move presentation logic into the view model, like joining a name with an optional salutation or formatting a date.
- It exposes ready-to-show strings, so
viewDidLoadjust doesnameLabel.text = viewModel.name. - Tests assert those strings without building a view controller, and view hierarchy changes don't break them.
- Think of MVVM as refined MVC: the view controller still exists, it just stops formatting.
The model changes from network updates while the screen is visible. How does your view model keep the view in sync?
- Network updates arrive off the main actor, so the view model applies them on
@MainActorand the view never renders a half-updated state. - In SwiftUI, an
@Observableview model invalidates only the views that read the changed properties. - In UIKit I'd use the same
@Observablemodel: iOS 26 tracks reads inupdateProperties()and layout methods automatically, and on earlier targets I'd usewithObservationTrackingor a closure. - I wouldn't let the network layer mutate view state directly, because then ordering bugs have no single owner.
Your team is debating MVC versus MVVM for a new app. What questions settle it?
- My production default is MVVM with a Router because it isolates presentation state (testable without UIKit) and navigation (reusable screens) from view lifecycle without VIPER's ceremony, and
@Observableavoids RxSwift/Combine binding overhead. - MVC is the exception, for static screens like Settings. What settles it: long-lived or prototype? Collections or complex stateful elements? Async updates from several sources?
- Multiple teams or AI agents editing it?
- Complexity and expected evolution matter far more than team size: optimize for changing code safely tomorrow, not writing it fast today.
Your team wants MVVM but refuses to adopt a reactive framework. Is that viable?
- Yes, because observation ships with the platform.
- On iOS 17 and later an
@Observableview model needs no third-party framework, and a plainonChangeclosure works on any target. - Immutable models passed through
initneed no binding at all. - The real decision is how state reaches the view on our minimum OS version.
- A reactive library is a long-term dependency the whole team must learn, so I'd only adopt one for stream-shaped work like debounced search.
A year after moving to MVVM, view models are 800 lines. What went wrong?
- The line count alone doesn't tell me much, so I'd look at what keeps changing the file.
- If networking, persistence or business rules moved in, the view model became the new massive view controller.
- I'd keep it to presentation state and user intents on the main actor, and move rules and resource access into services behind protocols, so each concern has one owner.
- I wouldn't split it into smaller view models mechanically.
- In review, a view model touching
URLSessionor the database directly is my signal to act.
Does AI-assisted development change how you'd architect an iOS app?
- Yes, it strengthens the case for structure.
- I now also optimize for safe, localized changes by AI agents.
- Two questions: can an agent change one responsibility without understanding unrelated ones, and can we verify it without running the whole app?
- With MVVM + Router, a selection change lands in the ViewModel and its tests, not navigation or rendering.
- AI makes boilerplate cheaper, not coupling or regressions.
- The limit: extra pass-through layers fragment context and cause partial edits.
- So I favor MVVM + Router and unit tests even for small production apps.
Read it in the app's source
Done with MVVM (+ Router)? Mark it complete. Nailing its cards builds this pumpkin, row by row.