Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 46 ยท Data, Networking and Persistence

MVVM and App Architecture in SwiftUI

Organize a SwiftUI app with view models, @MainActor, repositories and protocols, keep logic out of views, and learn when MVVM is more structure than you need.

Small SwiftUI apps are happy to keep everything in views. Then a screen grows: a network call, validation, sorting, a retry button. The view fills with logic that is hard to test and hard to read. Architecture is the set of decisions about where each kind of code lives so that growth stays manageable.

The most common pattern in SwiftUI apps is MVVM: Model, View, ViewModel. This lesson explains what each part is responsible for, how @MainActor and repositories fit in, and, just as important, when MVVM is more ceremony than a screen deserves. The SwiftUI snippets are read-only. The TryIt builds a complete view model with a fake repository so you can run the logic.

The roles

Three roles

Model Plain data and business rules.
View Describes the screen from state.
ViewModel Screen state and user actions.

The view never talks to the network. The model never knows about views.

1 / 2
  • Model: the data your app is about, such as Task, Product, Forecast, with rules that belong to the data itself (a task is overdue if its due date is past).
  • View: SwiftUI code that turns state into pixels and forwards user input as calls. It has no networking, no sorting algorithms and no validation rules.
  • ViewModel: a class that holds the state of one screen (the load state, the text in a search field, the selected filter) and offers actions the view can call. It turns model data into what the screen shows.
  • Repository (or service): an object that knows how to fetch and store models. It hides whether data comes from URLSession, a database or a cache, so the view model asks for "the tasks" and does not care where they live.

What a view model looks like

With the @Observable macro (see @Observable and Observation), a view model is an ordinary class:

Swift
import SwiftUI

@MainActor
@Observable
final class TaskListViewModel {
    private(set) var state: LoadState<[TaskItem]> = .idle
    var searchText = ""
    private let repository: TaskRepository

    init(repository: TaskRepository) {
        self.repository = repository
    }

    var visibleTasks: [TaskItem] {
        guard case .loaded(let tasks) = state else { return [] }
        let query = searchText.trimmingCharacters(in: .whitespaces)
        return query.isEmpty ? tasks : tasks.filter { $0.title.localizedCaseInsensitiveContains(query) }
    }

    func load() async {
        state = .loading
        do {
            state = .loaded(try await repository.fetchTasks())
        } catch {
            state = .failed("Couldn't load your tasks.")
        }
    }
}

And the view stays small:

Swift
struct TaskListView: View {
    @State private var viewModel: TaskListViewModel

    init(repository: TaskRepository) {
        _viewModel = State(initialValue: TaskListViewModel(repository: repository))
    }

    var body: some View {
        List(viewModel.visibleTasks) { task in
            Text(task.title)
        }
        .searchable(text: $viewModel.searchText)
        .task { await viewModel.load() }
    }
}

Some details worth understanding:

  • The view owns the view model with @State. @State keeps the instance alive across re-renders, as explained in Choosing the Right Property Wrapper. Creating it in init with State(initialValue:) lets you inject the repository.
  • private(set) on state. The view can read the state but only the view model can change it. Actions are the only way in.
  • visibleTasks is derived. Filtering is computed from state instead of stored in a second array that could fall out of date.
  • $viewModel.searchText works because @State on an @Observable object provides a binding to its properties.

Why @MainActor

SwiftUI reads state on the main thread. A view model changes state that views display, so it must change that state on the main thread too. Marking the class @MainActor makes the compiler enforce this: every property and method runs on the main actor unless you opt out.

This does not block the main thread while waiting for the network. try await repository.fetchTasks() suspends the function, the main thread is free to keep drawing, and the function resumes on the main actor when the data arrives. Only the actual work done by the repository, if it is not itself main-actor isolated, runs elsewhere. Swift 6's strict concurrency checking rewards this design: a main-actor view model that talks to a Sendable repository compiles cleanly. The wider picture is in Concurrency in iOS: MainActor, Tasks and Async Work.

Repositories and protocols

Define what the view model needs as a protocol. The real implementation uses the network; tests and previews use a fake:

Swift
protocol TaskRepository: Sendable {
    func fetchTasks() async throws -> [TaskItem]
}

struct RemoteTaskRepository: TaskRepository {
    let client: APIClient
    func fetchTasks() async throws -> [TaskItem] {
        try await client.get("/tasks")
    }
}

struct PreviewTaskRepository: TaskRepository {
    func fetchTasks() async throws -> [TaskItem] {
        [TaskItem(id: 1, title: "Write lesson", isDone: false)]
    }
}

Now the same view model works in the app, in a SwiftUI preview and in unit tests. The injection techniques are covered in The Environment and Dependency Injection.

A view model you can run

This stand-in has the same shape as the real thing, minus SwiftUI: a main-actor class, a repository protocol, derived state and a failure path.

Swift A view model with a fake repository

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.

Everything interesting about this screen is now testable with plain function calls: filtering, counting and error handling. No simulator is needed. Testing View Models and UI builds on exactly this.

Where does navigation and shared state go?

A view model should not create other screens. Let it expose state or callbacks, and let the view (or a router object, see Deep Links and Universal Links) decide what to present. State that several screens share, such as the signed-in user or a settings model, belongs in a shared @Observable object placed in the environment, not copied into each view model.

A common layering that scales well:

  • Views know view models.
  • View models know repositories and models.
  • Repositories know networking, storage and models.
  • Nothing below knows about the layer above.

When MVVM is not needed

MVVM is a tool, not a rule. SwiftUI views are already lightweight descriptions of state, and Apple's own sample code often keeps simple state right in the view. Skip the view model when:

  • The screen only displays data passed in from its parent, such as a row view.
  • The state is purely local UI state: a toggle, a text field, which section is expanded. @State in the view is the right home.
  • The logic is a one-liner. A view model with one property and no actions adds files without adding clarity.
  • Your data layer already does the work, for example a SwiftData @Query feeding a list. Wrapping it in a view model often duplicates what the framework provides.

Use a view model when a screen has asynchronous work, several states, non-trivial rules, or logic you want to test. A good habit is to start with state in the view and extract a view model when the view's body is no longer the most interesting thing in the file.

Also resist over-engineering the layers: a repository protocol is worth it when you have two implementations (real and fake). A "UseCase" class per button, generic base view models and coordinators for every flow often cost more than they save in an app of normal size.

Common mistakes

  • Putting UIKit or SwiftUI types in the view model. Keep it free of views so it stays testable. (Importing SwiftUI just for @Observable is fine.)
  • Forgetting @MainActor, then updating state from a background context. Swift 6 will point this out; do not silence it with @unchecked.
  • Creating the view model inside body. It would be recreated on every render and lose its state. Own it with @State.
  • Duplicated state: storing filteredTasks next to tasks. Derive the filtered list.
  • A view model per row when the row only displays a value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which code belongs in a view model rather than a view?

    View models hold screen state and logic. Layout and styling stay in the view.
  2. 2. What does @MainActor on a view model guarantee?

    Main-actor isolation lets the compiler enforce main-thread access. Awaiting a network call inside it suspends without blocking the thread.
  3. 3. Why define the repository as a protocol?

    A protocol allows different implementations behind the same interface, which makes previews and tests easy.
  4. 4. A screen shows one toggle that only affects its own appearance. What is usually best?

    Purely local UI state belongs in @State. A view model would add structure without benefit.
  5. 5. Why is it better to compute visibleTasks than to store a separate filtered array?

    Derived values always reflect the current source of truth. Two copies need extra code to stay consistent.

Summary

  • MVVM separates the model (data and rules), the view (rendering) and the view model (screen state and actions).
  • A repository hides where data comes from; define it as a protocol so fakes can replace it.
  • Mark view models @MainActor, own them with @State, expose state as private(set) and derive values instead of duplicating them.
  • Awaiting inside a main-actor view model does not block the UI.
  • Keep navigation decisions and shared app-wide state outside individual view models.
  • Skip the view model for simple, local, presentation-only screens; add it when a screen has async work, several states or logic worth testing.

Next: UserDefaults, @AppStorage and Files