In SwiftUI on iOS 17 and later, how do you declare a view model for a hotel search screen, and why mark it @MainActor?
answer
- a macro from Observation
- final class, not a struct
- reads in body are what subscribe
- the actor View is declared on
- intent methods instead of logic in body
basics
~20 sDeclare a final class with Observation's @Observable macro and @MainActor, holding the screen's state and intent methods. SwiftUI tracks the properties body reads, and main-actor isolation keeps every mutation on the actor body runs on.
solid answer
~40 sI write `@MainActor @Observable final class HotelSearchModel` with the screen's state as stored `var`s, mostly `private(set)`, plus intent methods such as `submit()`. A view that reads `model.results` in `body` forms a dependency on that property, so a change to a property it never read does not update it. `View` is declared `@MainActor`, so marking the model `@MainActor` puts both on one actor: the view calls synchronous members without `await`, and an `async` intent resumes on the main actor after awaiting the service, so `results = …` is never written from a background thread. In Swift 6 language mode the compiler enforces that isolation instead of leaving it to discipline. Validation, formatting and loading live in the model, so `body` only describes UI and the logic can be unit-tested without rendering a view.
code
swift · 32 linesimport SwiftUI
struct Hotel: Identifiable, Sendable { let id: UUID; let name: String }
protocol HotelSearching: Sendable {
func hotels(in city: String) async throws -> [Hotel]
}
@MainActor @Observable
final class HotelSearchModel {
var city = ""
private(set) var results: [Hotel] = []
private(set) var isLoading = false
private(set) var errorMessage: String?
private let search: any HotelSearching // a let is never tracked
init(search: any HotelSearching) { self.search = search }
var canSubmit: Bool { !city.isEmpty && !isLoading }
func submit() async {
guard canSubmit else { return }
isLoading = true
defer { isLoading = false }
do {
results = try await search.hotels(in: city) // resumes on the main actor
errorMessage = nil
} catch {
errorMessage = "Search failed. Try again."
}
}
}go deeper
Recall the declaration: an @Observable final class marked @MainActor, with state as stored properties and actions as methods the view calls.
Explain that body's reads create the dependency, that let and computed properties behave differently, and that an async intent resumes on the main actor after its await.
Show why isolation matters in Swift 6 language mode, where heavy work belongs, and how private(set) state plus intents keeps the screen testable.
Frame the view model shape as a team convention: one isolation rule, one ownership rule and intent methods every screen follows, so reviews check behaviour rather than style.
## What a SwiftUI view model is A **view model** is an object that holds one screen's state and the operations a person can trigger on it, so the view struct only describes what to draw. In a hotel search screen it owns the typed city, the results, a loading flag and an error message, and it exposes **intent methods** such as `submit()`. Since iOS 17, SwiftUI's preferred way to make such an object observable is **Observation**, not the older `ObservableObject` protocol. ## Declaring it with Observation Apple's guidance is to apply the `@Observable` macro to the type. The macro rewrites the class at compile time so reads and writes of its stored properties are reported to an observation registrar. - Use the **macro**, not the protocol: Apple's documentation warns that conforming to `Observable` by hand adds no observation at all. - It must be a **class**. The macro rejects structs, enums and actors, because views and async work need to share one instance. - Mark it `final` unless you need subclassing; nothing in Observation requires inheritance. - Only **stored `var` properties** are instrumented. A `private let search: any HotelSearching` dependency is never tracked, because it cannot change, so it needs no `@ObservationIgnored`. - **Computed properties** such as `canSubmit` are tracked through the stored properties they read. - Make state `private(set)` so every change goes through an intent the screen can test. ## How a view connects to it SwiftUI forms a dependency when a view's `body` **reads** a property of an observable object. If `body` reads `model.results` but not `model.errorMessage`, a change to the error message does not update that view. The model itself is owned once, typically in a `@State` property of the screen's parent, and passed down as a plain property. When a control needs a `Binding`, such as `searchable(text:)`, the view declares the model with `@Bindable` and passes `$model.city`. Ownership rules and `@Bindable` in depth belong to the lessons on view-owned state and on Observation-based models. ## Why @MainActor The `View` protocol is declared `@MainActor @preconcurrency`, so `body` and a view's other members run on the **main actor**. Marking the view model `@MainActor` places it on the same actor: 1. The view calls synchronous members (`model.canSubmit`) without `await`. 2. An `async` intent runs on the main actor until it reaches `await search.hotels(in:)`. The service runs wherever its own isolation places it, and the main actor is free while the call is suspended. 3. When the call returns, the method **resumes on the main actor**, so the assignment to `results` happens where `body` will read it. 4. In **Swift 6 language mode**, a plain class is not `Sendable`, and the compiler reports a data-race error when it is shared with code on another actor. `@MainActor` makes the class safe to share by confining it. `@MainActor` does not make the network call itself run on the main thread; heavy synchronous work such as parsing belongs in the service, not in a main-actor method. ## Keeping logic out of body SwiftUI re-runs `body` whenever a tracked dependency changes, so `body` should be a cheap description of UI. Put these in the view model instead: - validation such as whether the search can be submitted - formatting prices and dates for display - starting and cancelling loads, and mapping errors to messages - anything a unit test should check without building a view ## Common declarations compared | Declaration | Result in SwiftUI | |---|---| | `@MainActor @Observable final class` | tracked per property, isolated with the view | | `@Observable final class` without `@MainActor` | tracked, but async work can write it off the main actor and Swift 6 mode flags sharing it | | `final class: Observable` (no macro) | conforms but reports nothing, so views never update | | `final class: ObservableObject` without `@Published` | the older system, and nothing publishes changes | ## Where it is created Under the `State` property wrapper, used when building with Xcode 26 or earlier, the default value expression runs every time SwiftUI instantiates the view, so an expensive model initializer allocates copies that are thrown away; Apple suggests deferring creation with `task`. Building with Xcode 27 uses the `State()` macro, which instantiates the default value only the first time SwiftUI instantiates the view.
- Where should the hotel search view model be created, and does building with Xcode 27 change that?Create it once in the view that owns the screen's lifetime, usually in a parent's `@State`, and pass it down. Under the `State` property wrapper (Xcode 26 and earlier) the default value expression runs every time SwiftUI instantiates the view, so an expensive initializer allocates throwaway copies; Apple suggests deferring creation with `task`. With Xcode 27, `@State` is the `State()` macro, which instantiates the default value only the first time.
- Why can't the view model be a struct with the @Observable macro?The `@Observable` macro rejects structs: the compiler reports that it cannot be applied to a struct type. A view model must be one shared instance that views read and async work mutates later; copies of a struct would diverge. Plain value state that only one view needs belongs in that view's `@State` instead.
- Does @MainActor on the view model make its network calls run on the main thread?No. The intent runs on the main actor until `await search.hotels(in:)`; the service runs wherever its own isolation puts it, and the main actor is free while the call is suspended. The method resumes on the main actor to assign `results`. Keep heavy synchronous work such as decoding in the service, not in the main-actor model.
- Marking the view model @MainActor makes its network calls run on the main thread.
- Conforming a class to the Observable protocol is enough for SwiftUI to track it.
- A view updates whenever any property of an @Observable view model changes.
- View models should be structs so SwiftUI can diff them cheaply.
- Validation and formatting belong in body because body reruns on every change.
Assumes iOS 17+ for Observation; with Xcode 27 @State is the State() macro, which creates a class-typed default once.