In SwiftUI, what does marking a model class with the @Observable macro give you, and when do you add @ObservationIgnored to a property?
answer
- a macro, not a protocol
- no wrapper on each property
- stored var gets tracking accessors
- opt out what no view shows
basics
~20 sThe @Observable macro from Apple's Observation framework makes a class's stored var properties observable with no @Published, so a SwiftUI view that reads one redraws when it changes. @ObservationIgnored opts out a property that no view displays.
solid answer
~40 sAttaching `@Observable` to a class (iOS 17 and later) generates an `ObservationRegistrar` plus tracking accessors for each stored instance `var`, and conforms the class to the `Observable` protocol. There is no `@Published` and no `ObservableObject`: a view that reads `cart.items` in `body` is updated when `items` changes. A `let` constant and a static property are not instrumented, and a computed property such as `itemCount` is tracked through the stored properties its getter reads. I add `@ObservationIgnored` to stored state that no view should react to: a cache, an in-flight `Task` handle, a sync timestamp. The catch is that a view reading an ignored property never refreshes because of it. The macro only applies to classes, and conforming to `Observable` by hand adds no observation at all.
code
swift · 26 linesimport Foundation
import Observation
struct CartItem: Identifiable {
let id: UUID
var name: String
var price: Decimal
var quantity: Int
}
@Observable
final class CartModel {
var items: [CartItem] = [] // tracked
var couponCode = "" // tracked
var isCheckingOut = false // tracked
@ObservationIgnored
var lastSyncedAt: Date? // never redraws a view
@ObservationIgnored
private var syncTask: Task<Void, Never>?
var itemCount: Int { // tracked through items
items.reduce(0) { $0 + $1.quantity }
}
}go deeper
Recall that @Observable is a macro on a class, that stored vars are tracked with no @Published, and that @ObservationIgnored opts a property out.
Explain what the macro generates (registrar, tracking accessors, protocol conformance) and why let, static and computed properties behave as they do.
Show judgment about @ObservationIgnored: which state is safe to ignore, and how an ignored property read by a view produces stale UI that is hard to spot in review.
Frame the model as the team's unit of observation: what goes in it, what is ignored and documented, and how reviewers keep wrappers from the older ObservableObject model out of new code.
## What the macro generates The **`@Observable`** macro belongs to Apple's **Observation** framework, which ships with iOS 17, macOS 14, tvOS 17, watchOS 10 and visionOS 1. It is the way a SwiftUI app makes a reference-type model observable. When you attach it to a class, the compiler expands it into ordinary Swift code: - a private **`ObservationRegistrar`**, the object that records reads and announces writes; - **tracking accessors** for each eligible stored property, so every getter reports an *access* and every setter wraps the write in a *mutation*; - a conformance to the **`Observable`** protocol, which tells SwiftUI and other APIs that the type supports observation. Apple's documentation is direct about the last point: conforming a type to the `Observable` protocol on its own adds no observation. The protocol is only a marker. The macro does the work, so you always write `@Observable`, never `: Observable` alone. ```swift @Observable final class CartModel { var items: [CartItem] = [] var couponCode = "" @ObservationIgnored var lastSyncedAt: Date? var itemCount: Int { items.reduce(0) { $0 + $1.quantity } } } ``` ## Which properties are tracked The macro instruments **stored instance `var` properties** that are not marked `@ObservationIgnored`. Everything else falls into one of the rows below. | Declaration in the class | Tracked? | Why | |---|---|---| | `var items: [CartItem]` | Yes | stored instance `var`: the macro adds tracking accessors | | `let id = UUID()` | No | a constant can never change, so there is nothing to observe | | `static var shared` | No | the macro only instruments instance properties | | `var itemCount: Int { ... }` | Through `items` | the getter reads `items`, and that read is tracked | | `@ObservationIgnored var lastSyncedAt` | No | explicitly opted out | Optionals and arrays work as they are, with no extra wrapper. Apple's migration guide lists tracking optionals and collections of objects as one of the gains over `ObservableObject`. The macro accepts **classes only**. Applied to a struct, an enum or an actor, it stops the build with an error such as "'@Observable' cannot be applied to struct type". Value-type state that one view owns is what `@State` with a struct is for. ## Opting out with @ObservationIgnored **`@ObservationIgnored`** is an accessor macro that stops the `@Observable` macro from adding tracking to one property. Typical candidates are stored properties that change but are not something any view shows: - a cache or memoised lookup the model rebuilds on demand; - a handle to work in flight, such as a `Task<Void, Never>?` used to cancel a pending sync; - bookkeeping such as a `lastSyncedAt` timestamp used to throttle network calls; - injected dependencies, such as an API client, that are not UI state. The cost is easy to miss. If a view *does* read an ignored property, SwiftUI is never told when it changes, so that view keeps showing the old value until something else makes it redraw. The rule of thumb is to ignore only what no view displays, and to leave a comment saying why. ## Using the model from SwiftUI The usual flow has four steps: 1. Declare the class with `@Observable`. 2. Create one instance in the view, scene or `App` that owns it, stored with `@State`. 3. Hand it to children as a plain property, or place it in the environment with `environment(_:)`. 4. Read its properties in `body`; SwiftUI updates the views whose `body` read a property that changed. None of the older object wrappers (`@StateObject`, `@ObservedObject`, `@EnvironmentObject`) is needed, because those were built for `ObservableObject` and its `@Published` properties. Writing a property from a button action needs no wrapper either: the model is a class, so `cart.couponCode = ""` mutates the shared instance and the registrar announces the change. ## Mistakes reviewers catch - Keeping `@Published` or the `ObservableObject` conformance around after adding `@Observable`. Observation uses neither. - Declaring `class CartModel: Observable` and expecting views to update. - Marking a displayed property `@ObservationIgnored` "for performance", then filing a bug about stale text. - Trying to make a struct `@Observable` instead of holding it in `@State`. - Assuming computed properties are invisible: they update views correctly as long as their getter reads tracked stored properties. How the macro expands, as a Swift language feature, belongs with the Swift material on macros; what matters on the SwiftUI side is that each tracked read in `body` registers that view, and each tracked write notifies it.
- Can you apply @Observable to a struct or an actor?No. The macro emits a compile error for struct, enum and actor types; it is meant for classes, whose single shared instance many views can read. State that belongs to one view and has value semantics goes in `@State` as a struct instead.
- Why does a badge that reads the computed itemCount still update when an item is added?Calling `itemCount` in `body` runs its getter, and the getter reads the stored `items` property. That read goes through the tracking accessor, so the badge view is registered for `items` and is updated when `items` changes, even though `itemCount` itself has no accessor generated for it.
It is like a library that stamps a card every time someone opens a particular shelf: when that shelf is restocked, only the people with a stamp for it get a call. @ObservationIgnored is a shelf with no stamp, so nobody is called when it changes.
- @Observable classes still need @Published on each property
- Conforming a class to the Observable protocol by hand makes it observable
- @Observable works on structs just as well as classes
- @ObservationIgnored makes a property private or read-only
- Computed properties on an @Observable class never update views