2 of 22 · 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
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
Owns navigation, so screens never push each other.
@MainActor
final class NoteRouter: NoteRouting {
weak var navigation: UINavigationController?
func showSaved() {
navigation?.popViewController(animated: true)
}
}View controller
Binds and forwards. Nothing to unit test here, by design.
final class NoteViewController: UIViewController {
private let viewModel: NoteViewModel
override func viewDidLoad() {
super.viewDidLoad()
render()
}
// Re-runs when any property read inside changes (iOS 17+).
private func render() {
withObservationTracking {
saveButton.isEnabled = viewModel.canSave
errorLabel.text = viewModel.error
} onChange: { [weak self] in
Task { @MainActor in self?.render() }
}
}
@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)
}Initializers and outlets for the view controller are omitted.
Trade-offs, and what experts watch for
- +Presentation logic is testable without UIKit.
- +Navigation changes without touching screens.
- -Every screen gets a ViewModel, even trivial ones.
- -One more object per flow, and its lifetime to manage.
- Massive ViewModel is the next failure mode. When a ViewModel has a second reason to change (business rules, data access, flow), pull an interactor out, or go to VIPER for that component.
- Bindings: on iOS 17+,
withObservationTrackingreplaces hand-rolled closures and Combine for@ObservableViewModels. On iOS 26, UIKit tracks@Observablereads automatically inupdateProperties()andlayoutSubviews(). - Keep ViewModels
@MainActorand their outputs value types. Async work lives in services; the ViewModel awaits and updates state.
When I'd use it
| Most production UIKit features | MVVM with a Router. |
|---|---|
| A component with several independent reasons to change | VIPER for that component. |
| A static screen | No ViewModel. |
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 and never imports UIKit.
- The Router owns navigation and building the next screen.
- The view controller only binds and forwards.
- That makes presentation logic unit-testable and lets flows change without touching screens.
- The cost is a ViewModel even on simple screens, and when one ViewModel gets a second reason to change, I pull out an interactor.
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?
- Observe it, and update on the main actor.
- Network updates arrive off-main, so the view model hops to
@MainActorbefore mutating state. - In SwiftUI, an
@Observableview model re-renders exactly the views that read the changed properties. - In UIKit, use
withObservationTrackingto re-run your render function, or Combine@Publishedon older targets. - MVVM itself doesn't require any binding framework.
Your team is debating MVC versus MVVM for a new app. What questions settle it?
- My default for a production app is MVVM with a Router; with @Observable it needs no binding framework, so it stays light.
- MVC is the exception, for simple static screens like Settings.
- What settles it: long-lived or a prototype?
- Collections or complex, stateful elements?
- Async updates from several sources?
- Other teams or AI agents editing it?
- Complexity and expected evolution matter far more than team size.
- Optimize for how easy the code is to change correctly tomorrow, not to write today.
Your team wants MVVM but refuses to adopt a reactive framework. Is that viable?
- Yes.
- Observation ships with Swift:
@Observableneeds no third-party framework, and a plainonChangeclosure works on any deployment target. - Immutable models handed in through
initneed no binding at all. - The real decision is how state reaches the view on your minimum OS version, not whether to adopt a reactive library you'll carry for years.
A year after moving to MVVM, view models are 800 lines. What went wrong?
- The view model became the new massive view controller: networking, persistence and business rules moved in.
- Keep it to presentation state and user intents on the main actor.
- Move resource access, business rules and state machines into domain services or interactors behind protocols, so each concern has one owner.
- In review, a view model that touches
URLSessionor the database directly is the red flag.
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: needless indirection confuses AI too.
- So I favor MVVM + Router and unit tests even for small production apps.