skip to content

In SwiftUI with Observation, when is a per-screen view model overhead, and what does the model-view approach with environment models do instead?

level: middleimportance: should knowfreq 52%

answer

  1. views can read models directly
  2. a copy that goes stale
  3. shared models injected by type
  4. screen-only state earns an object

basics

~20 s

A per-screen view model is overhead when it only copies or forwards an observable model's properties. In the model-view approach, shared @Observable models live in the environment, views read them directly with tracked reads, and logic sits in model methods.

solid answer

~40 s

With Observation, a view can read an `@Observable` model directly and SwiftUI tracks exactly the properties `body` reads, so a screen no longer needs its own object just to republish data. In the model-view approach the app owns shared models, such as a `BookingSession`, in `@State` on the `App`, injects them with `environment(_:)`, and views read them with `@Environment(BookingSession.self)`; for controls that need bindings, `body` declares a local `@Bindable` copy of the reference. A per-screen view model is overhead when it copies or forwards those properties: the copy goes stale and every change is written twice. It earns its place when the screen has state no one else needs, such as loading, errors, validation or a cancellable draft, when it coordinates several services, or when its logic needs tests without rendering a view.

code

swift · 30 lines
swift
import SwiftUI

@MainActor @Observable
final class BookingSession {
    var nights = 1
    var guests = 2
    var isValid: Bool { nights > 0 && guests > 0 }
}

@main
struct HotelApp: App {
    @State private var session = BookingSession()   // one shared source of truth
    var body: some Scene {
        WindowGroup {
            StayEditor()
                .environment(session)
        }
    }
}

struct StayEditor: View {
    @Environment(BookingSession.self) private var session
    var body: some View {
        @Bindable var session = session   // bindings into the shared model
        Form {
            Stepper("Nights: \(session.nights)", value: $session.nights, in: 1...30)
            Stepper("Guests: \(session.guests)", value: $session.guests, in: 1...8)
        }
    }
}

go deeper

for a junior

Know that with Observation a view can read an @Observable model from the environment directly, and that a view model is optional.

for a middle

Explain how environment(_:), @Environment(Type.self) and a local @Bindable fit together, and why copying shared values into a view model goes stale.

for a senior

Judge screen by screen whether there is state of its own to justify a view model, and keep one source of truth when mixing both shapes.

for a principal

Weigh consistency against fit: a team-wide rule for when a screen gets a view model, so reviewers ask whether the object holds screen-only state.

## Two ways to feed a screen In SwiftUI apps that adopt **Observation** (iOS 17 and later), teams usually pick between two shapes for a feature such as hotel booking: - **View model per screen (MVVM):** each screen gets an `@Observable` class that holds its state and actions, and the view reads only that object. - **Model-view, often called MV:** a few shared `@Observable` domain models, such as a `BookingSession` or a `Favorites` list, are owned near the root and placed in the environment; views read and change them directly, and logic lives in the models' methods. Both are legitimate. The question is what an extra object buys on a given screen. ## How the model-view approach works 1. The `App` owns the shared model in `@State`, which makes SwiftUI keep one instance. 2. It injects the model with `environment(_:)`, so any descendant can reach it without passing it through every initializer. 3. A view reads it with `@Environment(BookingSession.self)`. Observation records each property `body` reads, so a stepper bound to `nights` does not update a view that only shows `guests`. 4. For controls that need a `Binding`, `body` declares `@Bindable var session = session` and passes `$session.nights`; Apple's documentation shows `@Bindable` used on local variables this way. 5. Rules such as `isValid` are computed properties or methods on the model, so `body` stays a description of UI. Reading an object type that no ancestor injected makes SwiftUI throw an exception; declaring the property optional returns `nil` instead. The lesson on Observation-based models covers that in depth. ## When a view model is overhead A per-screen object costs a type, an initializer, an injection path and tests. It is overhead when: - it only **forwards** properties of a shared model, so the view could read the model itself; - it **copies** a shared value at init, such as the selected room, and then goes **stale** when another screen changes the original; - every edit is written twice, once to the view model and once back to the model. SwiftData adds one more pull toward views: `@Query` is a `DynamicProperty`, and SwiftUI gives dynamic properties their values as part of updating a view, before computing its `body`. Fetching therefore tends to sit in the view, and wrapping it in a view model means rebuilding the fetch by hand. That wiring is covered with SwiftData's SwiftUI integration. ## When a view model earns its place | Screen trait | Better fit | |---|---| | shows and edits shared booking data | model-view: read the environment model | | loads results with loading and error states | view model owning that transient state | | a draft the person can cancel without touching shared data | view model holding the draft | | coordinates search, pricing and analytics for one action | view model with injected services | | validation rules that need unit tests without views | view model, or methods on the domain model | The deciding question is whether the screen has **state of its own**. Loading flags, error messages, a cancellable draft and multi-service orchestration belong to the screen, not to the shared model, and they are easier to test in an object than in a view. ## Mixing the two Most real apps mix them. A results screen keeps an `@MainActor @Observable` view model for its search state and reads the shared `BookingSession` from the environment, or receives it through its initializer, for the dates and guests. The important rule is a **single source of truth** for each value: the view model holds what only that screen needs and reads shared values from the shared model rather than copying them. ## Testing each shape Both shapes stay testable if logic lives outside `body`: - In the model-view approach, test the shared model directly: create a `BookingSession`, call its methods, and assert on its properties. - With a view model, construct it with fake services through its initializer and drive its intent methods, then assert on its `private(set)` state. - In either case, previews inject a sample model with `environment(_:)` or pass a view model built with fakes, so every screen can be shown in each state without a network. ## Pitfalls - Copying shared values into a view model at init and expecting them to stay current. - Wrapping every screen in a view model by habit, which doubles the code for display-only screens. - Putting screen-only state such as `isLoading` on a shared model, so two screens fight over it. - Reading `@Environment` inside a view model; SwiftUI never installs a class, so it cannot see injected values.

  • A results screen needs both shared booking dates and its own loading state; where does each live?
    The dates stay in the shared `BookingSession`, read from the environment or passed in, so every screen sees one value. The loading flag, error message and results belong to an `@MainActor @Observable` view model for that screen, because no other screen needs them. The view model reads the dates from the session when it searches instead of copying them at init.
  • Why does SwiftData's @Query push fetching toward views rather than view models?
    `@Query` is a `DynamicProperty`, and SwiftUI supplies dynamic properties as part of updating a view, just before computing its `body`. A view model is not a view, so nothing would update it there. A view model that owns fetching has to build its own fetch through the model context instead, which is why many SwiftData screens keep `@Query` in the view.

  • Every SwiftUI screen needs its own view model, whatever it does.
  • Copying shared values into a view model at init keeps them in sync.
  • Views can't edit an environment model without @EnvironmentObject.
  • Screen-only state such as isLoading belongs on the shared app model.