skip to content

A SwiftUI hotel results screen needs a view model whose search service differs in previews and per subtree; where should the screen build that view model, and how does it get the service?

level: seniorimportance: should knowfreq 42%

answer

  1. where the service is chosen
  2. not in the view's init
  3. create the model in task
  4. or let the parent build it
  5. services through the model's init

basics

~20 s

Build the view model where the chosen service is actually available: in the screen's task, held in optional @State, or in a parent or feature entry that picks the service and passes the model in. Either way the model takes the service through its own initializer as a protocol type.

solid answer

~50 s

The view model should not pick its own services, and the view struct's `init` is the wrong place to build it: the initializer runs every time the parent's `body` builds the struct, and it runs before the view's environment is installed (the environment lesson explains what such an early read returns). Two placements work. **Build it in `task`:** hold `@State private var model: ResultsModel?` and, on the first `task` run, create `ResultsModel(city:search:)` from the screen's environment value, so a preview's `.environment(\.hotelSearch, FakeHotelSearch())` reaches it; the cost is a placeholder on the first frame. **Let the parent build it:** a feature entry point that knows which service to use constructs the model once, keeps it in its own `@State` and passes it down, so the first frame is ready and a preview passes a model built with a fake. In both, the model is a `@MainActor @Observable` class that takes its dependency as a `Sendable` protocol type through `init`.

code

swift · 29 lines
swift
import SwiftUI

struct Hotel: Identifiable, Sendable { let id: UUID; let name: String }

protocol HotelSearching: Sendable {
    func hotels(in city: String) async throws -> [Hotel]
}

struct LiveHotelSearch: HotelSearching {
    func hotels(in city: String) async throws -> [Hotel] { [] }   // network call elided
}

extension EnvironmentValues {
    @Entry var hotelSearch: any HotelSearching = LiveHotelSearch()
}

@MainActor @Observable
final class ResultsModel {
    let city: String
    private(set) var hotels: [Hotel] = []
    private let search: any HotelSearching

    init(city: String, search: any HotelSearching) {
        self.city = city
        self.search = search
    }

    func load() async { hotels = (try? await search.hotels(in: city)) ?? [] }
}

go deeper

for a junior

Recall that a view model receives its services from outside, and that a screen can build it in task or receive it from its parent.

for a middle

Explain why the view's init is the wrong place to build the model, and how optional @State plus task defers construction until the environment is available.

for a senior

Choose between creating the model in task and building it in the parent, and keep the model's dependencies as Sendable protocol types injected through init.

for a principal

Decide where a feature's services are chosen, an environment value or a feature factory, and make that one rule so previews and tests swap fakes the same way everywhere.

## The design question A hotel results screen shows hotels from a search service. Production uses the live network client, previews and tests want a fake, and one branch of the app might use a cached variant. The screen therefore needs a view model whose service is chosen **outside** it. Where the screen builds that model decides two things: which service the model ends up holding, and how long the model lives. ## Why not in the view's init The obvious place, `init(city:)`, building `ResultsModel(city: city, search: search)` from an `@Environment(\.hotelSearch)` property, fails twice: - **Timing.** A view's initializer runs when its parent's `body` constructs the struct, before SwiftUI has supplied the view's environment. The model captures the key's default rather than the value an ancestor or a preview set; why that read returns the default is covered with environment values. - **Repetition.** The initializer runs on every parent update. Even when the result is stored with `State(initialValue:)`, which keeps only the first instance, the model is allocated again on each run and thrown away. ## Fix 1: create the model where the environment is installed Hold the model as optional state and create it the first time the view's `task` runs: 1. Declare `@State private var model: ResultsModel?` so SwiftUI keeps the instance across redraws. 2. In `.task`, return early if a model exists, otherwise build it from the environment value and start loading. 3. In `body`, show a placeholder while `model` is `nil`. This is the same deferral Apple suggests for any expensive observable state: it avoids allocating the model on every initialization of the view struct and runs only after the environment is available. The early return matters because `task` runs again whenever the view reappears, for example after the user pops back to it. ## Fix 2: let the parent build it The other fix moves the decision up one level. The parent, or a feature entry point that already knows which service to use, constructs `ResultsModel(city:search:)`, keeps it in its own `@State` or in a model it owns, and passes it down as a plain property. This is plain **initializer injection** with a **composition root**: one place decides which live or fake services a feature gets. - Do not construct the child's model inline in the parent's `body`; each body run would create a fresh model and the child would lose its loaded results. - Keep the instance somewhere stable, so redraws reuse it. - Previews and tests then build the model directly with a fake and never touch the environment. ## Keeping the view model injectable Whichever fix you pick, shape the view model so injection is trivial: - Take each dependency as a **protocol type** in `init`, stored as a `private let`, which Observation never tracks. - Make the protocol `Sendable`, so a main-actor model can call it across isolation in Swift 6 language mode. - Keep SwiftUI property wrappers out of the model; it receives services, it does not look them up. - Keep the model `@MainActor` and `@Observable` so the view can read it directly. ## Choosing between the fixes | Concern | Create in `task` | Parent builds it | |---|---|---| | Where the service is chosen | the environment, per subtree | the parent or feature entry | | Previews | override the environment value | pass a model built with a fake | | First frame | shows a placeholder until `task` runs | ready on first render | | Unit tests of the model | construct it directly | construct it directly | Teams that already route services through custom environment values tend to prefer the first; teams with an explicit feature factory prefer the second. Defining environment values, and choosing between the environment and initializer parameters for a view, are covered with environment injection, and `task` timing with the lesson on appearance and async work.

  • When would you choose the parent-builds approach over creating the model in task?
    When the first frame must show content without a placeholder, or when a feature factory already chooses services for a whole flow. Creating the model in `task` suits teams that route services through environment values, because a subtree or a preview can then swap the service with one modifier.
  • With the task-based fix, how does a preview swap in a fake service?
    The preview applies `.environment(\.hotelSearch, FakeHotelSearch())` to the screen. The model is now created inside `task`, after SwiftUI has installed the view, so it reads the fake. Under the parent-builds approach the preview instead constructs `ResultsModel(city:search:)` with the fake and passes it in.
  • What goes wrong if the parent writes ResultsScreen(model: ResultsModel(city: city, search: search)) in its body?
    Every run of the parent's `body` builds a new, empty model, so the child loses its loaded hotels whenever the parent redraws. The parent must keep the instance somewhere stable, such as its own `@State`, and pass that same instance down.

  • The view's init is the right place to build its view model from environment services.
  • A view model should look up its own services rather than receive them.
  • Creating the child's view model inline in the parent's body keeps it alive across redraws.
  • A global singleton service is the easiest way to swap fakes per preview.