Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 146 ยท Platforms and Ecosystem

App Architecture: MVC, MVVM and Clean Boundaries

Structure a real Swift app - MVC, MVVM, view models with Observation, repository protocols, dependency injection and a composition root, with runnable console examples.

Small programs fit in one file. Real apps do not: they have screens, networks, databases and rules, and they change every month. Architecture is the answer to "where does this code live?" A good structure lets you change the user interface without touching the business rules, swap a real server for a fake in tests, and find a bug in minutes instead of hours.

There is no single correct pattern, and the names (MVC, MVVM, Clean) are loose. What matters is a few ideas you can apply in any of them: separate what the app knows from how it is shown, depend on protocols at the boundaries, and build the object graph in one place. This lesson teaches those ideas with a small to-do feature that runs as a console program, so the structure is easy to see without any UI framework. The same code drops into SwiftUI, UIKit, a server or a command-line tool unchanged.

The classic split: Model, View, Controller

MVC divides an app into three roles:

  • Model: the data and rules ("a task has a title and can be completed"). It knows nothing about screens.
  • View: what the user sees and touches.
  • Controller: the glue. It reacts to user actions, changes the model and tells the view what to show.
flowchart LR
    U["User"] -->|"taps"| V["View"]
    V -->|"action"| C["Controller"]
    C -->|"updates"| M["Model"]
    M -->|"new data"| C
    C -->|"configures"| V

In MVC the controller sits in the middle: the view and the model do not talk to each other directly.

Swift MVC with a console view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The model is plain Swift with no print. You could test TaskList without any view. The view receives finished strings, so it contains no logic. The controller holds the knowledge of how a Task becomes a row.

MVC is simple and fine for small screens. Its common failure is the massive controller: because the controller is the only place where model and view meet, formatting, validation, networking and navigation all pile up there. In UIKit this is the famous "Massive View Controller", a class of a thousand lines that cannot be tested without creating a screen. MVVM is one way to fix that.

MVVM: a view model that the view observes

MVVM adds a view model between the model and the view. It holds the state of the screen in a form that is ready to display (already formatted strings, flags such as isLoading), and it exposes actions the view can call. The view only shows the state and forwards user events. It does not know about the model, and the view model does not know the view exists.

flowchart LR
    V["View"] -->|"calls actions"| VM["ViewModel"]
    VM -->|"state changes (observed)"| V
    VM -->|"uses"| M["Model and services"]

The view observes the view model's state. The view model never holds a reference to the view.

Swift's Observation framework (see Observation and @Observable) is a natural fit: mark the view model @Observable, and anything that reads its properties is told when they change. SwiftUI does this automatically; the example below does it by hand with withObservationTracking, so you can watch the mechanism.

Swift A view model driven by observation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each render call reads some properties inside the tracking closure; when one of them later changes, onChange fires once. A real UI framework re-runs the rendering code at that point. The view model contains all the decisions (when the Add button is enabled, what the summary says) and is a plain class, so you can test it by calling add() and checking tasks and summary, with no UI at all.

On Apple platforms, SwiftUI re-renders a view automatically when an @Observable property that its body read changes. You normally do not call withObservationTracking yourself; it is shown here so that the "magic" has no secrets. See the SwiftUI overview.

Clean boundaries: depend on a protocol

The to-do list above forgets everything when the program ends. Real apps save to disk or talk to a server. If the view model creates a URLSession or a database itself, it becomes impossible to test and hard to change. The fix is a boundary: the view model depends on a small protocol that describes what it needs, and the real implementation is supplied from outside.

flowchart TD
    UI["UI layer<br/>(views, view models)"] --> D["Domain<br/>(models, rules, repository protocols)"]
    DATA["Data layer<br/>(database, network, files)"] --> D

Arrows show who knows about whom. UI and data both depend on the domain; the domain depends on nothing.

The domain layer owns the protocol (TaskRepository). The data layer implements it. The UI layer receives something that conforms to it. Because dependencies point inward toward the domain, you can replace a database with an in-memory fake, or the UI with a command-line tool, without touching the rules. This is the core of what people call clean architecture.

Swift Repository protocol, real and fake, injected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The screen has no idea whether its repository is a database, a server or a dictionary. The failing BrokenRepository makes the error path testable in two lines, a case that is nearly impossible to trigger with a real network. Note two details: the screen updates tasks only after the save succeeded, and the protocol methods are async throws so any implementation (disk, network) can fit. The protocol also inherits from Sendable, because the main-actor screen hands the repository to code running elsewhere, and the compiler insists that such a value is safe to share (see Sendable).

The composition root

Somewhere the concrete types must be chosen and connected. That place is the composition root: usually @main, the App struct or a small AppEnvironment factory. Every other type receives its dependencies through its init (constructor injection) and never reaches for a global singleton or creates its own collaborators. A quick check: if you cannot construct a type in a test without a real network or disk, a dependency is hiding inside it.

Choosing a pattern

Question Good fit
Tiny screen, little logic MVC, or even state in the view
Screen with formatting, validation, loading states MVVM
Several features sharing rules and storage Domain layer with repository protocols
Complex flows between screens Add a coordinator/router object that owns navigation

Keep these habits whatever you pick:

  • One direction of data flow. User action in, state out. Avoid views and models calling each other in circles.
  • Value types for data, reference types for identity. Models as structs (see value vs reference), view models and services as classes or actors.
  • Small protocols, not god protocols. A repository with five methods that every fake must implement is a smell. Split by use.
  • No UI imports in the domain. If the domain file imports SwiftUI or UIKit, the boundary has leaked.
  • Do not over-engineer. Three layers and ten protocols for a two-screen app cost more than they save. Add a boundary when you need a fake, a second implementation or a clearer test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main problem the "massive controller" describes?

    Formatting, validation, networking and navigation all end up in the controller, making it long and hard to test.
  2. 2. In MVVM, what does the view model hold?

    The view observes the view model's state; the view model never needs to know the view exists.
  3. 3. Why does the screen depend on any TaskRepository and not on a concrete class?

    Depending on a protocol at the boundary lets you swap implementations without changing the screen.
  4. 4. What is a composition root?

    It is usually the app entry point. Everything else receives its dependencies through init.
  5. 5. Which sign shows that the domain layer has leaked?

    Domain code should not depend on UI frameworks, otherwise it cannot be reused or tested without them.

Summary

  • Architecture decides where code lives so that UI, rules and storage can change independently.
  • MVC puts logic in a controller between model and view; it is simple but the controller tends to grow.
  • MVVM moves screen state and actions into an observable view model that the view merely displays.
  • Define repository protocols in the domain, implement them in a data layer, and inject them through init.
  • Create the object graph once, in a composition root; use fakes and failing implementations to test every path.
  • Prefer the smallest structure that works, and add boundaries when a test or a second implementation needs them.

Next: Security: Keychain, CryptoKit and Safe Parsing