Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 146 ยท Platforms and Ecosystem

Observation and @Observable

Learn the Swift Observation framework - the @Observable macro, per-property tracking, withObservationTracking, @ObservationIgnored, computed and nested models, Observations streams and SwiftUI use.

Many programs need to answer one question: "something changed, who needs to know?" A screen must redraw when the data it shows changes. A cache must drop an entry when its source changes. A log must record a setting that was switched. The classic answers are callbacks, delegates, notification centers and reactive streams. Swift ships a smaller, built-in answer in the Observation framework: you mark a class with @Observable, and Swift records which properties any piece of code reads, then tells that code when one of those properties changes.

The Observation module is part of the standard Swift distribution, not only an Apple framework, so every example in this lesson runs on this site. SwiftUI is the best-known client, and you saw it used in the SwiftUI overview, but Observation itself knows nothing about user interfaces. This lesson explains the mechanism so SwiftUI stops feeling like magic. It builds on classes, macros and property observers.

The @Observable macro

Write import Observation, put @Observable in front of a class, and declare ordinary stored properties:

Swift
import Observation

@Observable
final class Player {
    var name = "Ada"
    var score = 0
}

The macro rewrites each stored property into a computed property backed by a hidden stored one, and it adds an observation registrar to the class. A read of score tells the registrar "somebody accessed score"; a write tells it "score is about to change". The registrar connects the two sides. You never write that code, and you never write @Published on each property.

flowchart LR
    R["Code reads player.score<br/>inside a tracking scope"] --> G["Registrar records:<br/>this scope depends on score"]
    W["Code sets player.score"] --> N["Registrar looks up<br/>scopes that read score"]
    G --> N
    N --> C["onChange runs for those scopes only"]

Reads register a dependency; writes notify only the scopes that depend on the written property.

The key idea is per-property tracking. A scope that read score is told about score changes and is never told about name changes.

Watching a change with withObservationTracking

The low-level API is withObservationTracking(_:onChange:). The first closure runs immediately, and every observable property it reads is tracked. The second closure runs once when the first of those properties is about to change.

Swift Tracking only what was read

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.

Three rules are visible here:

  1. Changing name does not call back, because the tracked closure never read it.
  2. The callback runs just before the new value is stored (like willSet), so inside it player.score still has the old value.
  3. The tracking is one-shot. After the first notification it is finished. To keep watching, start tracking again, usually inside the callback.

The one-shot design is deliberate. A UI framework re-runs the code that builds the screen when something changes, and that re-run reads the properties again and so sets up new tracking. You get the right set of dependencies each time, even when an if made the code read different properties on the second pass.

Observing repeatedly

Here is a tiny render loop. onChange only sets a flag ("the screen is stale"); the loop then redraws, which reads the properties again and registers fresh tracking. Real UI frameworks do the same, just much more efficiently.

Swift Re-arming the tracking after each change

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.

The first line draws the starting value. Changing mode marks nothing stale, so no redraw happens. Each change of target sets the flag; the redraw prints the new value, because by then the value has been stored, and it starts a new round of tracking. The shape to remember is: run the reading code, get one notification, run it again.

Real frameworks coalesce many changes into one redraw. If your code is a plain script and you just want a stream of values, prefer the async Observations sequence shown below.

What the macro does not track

@Observable only tracks stored properties of the class itself. Four cases are worth knowing.

Computed properties have no storage, but they are tracked indirectly. If a computed property reads tracked stored properties, a scope that reads the computed property depends on those stored ones.

Swift Computed properties follow their inputs

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.

@ObservationIgnored opts a stored property out of tracking. Use it for caches, loggers, delegates and anything that must not trigger updates.

Swift @ObservationIgnored

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.

Nested observable objects work because the inner object is itself observable. Reading library.owner.name registers a dependency on library.owner and on that name. Replacing the whole owner or changing its name both notify.

Structs and enums cannot be marked @Observable. The macro needs a reference type, because observers must watch one shared object. Trying it gives a clear error:

Swift @Observable needs a class (fails on purpose)

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.

The compiler complains that '@Observable' cannot be applied to struct type 'Settings'. Make it a final class. Value types do not need the feature: when a value type is stored in a property of an observable class, assigning a new value (or mutating a field) counts as writing that property.

Observing as an async stream

Newer Swift versions add Observations, which turns tracking into an AsyncSequence: it yields a value now and again after each change, using the tracking trick for you. This reads like ordinary async sequences code and avoids re-arming by hand.

Swift Observations as an async sequence

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.

The loop prints 0 first (the starting state), then each new value up to 3, and stops. The pause between writes matters: the stream reports the latest value when it next gets to run, so two writes in quick succession can be delivered as one update. That batching is intentional and is the same trade SwiftUI makes.

If you are writing tests for a model, prefer asserting on the model's properties directly. Reach for tracking only when the thing you are testing is the notification itself.

Observable in SwiftUI (read-only)

In SwiftUI, a View that reads properties of an @Observable model inside body gets exactly the tracking you just saw, and only those properties trigger a redraw. The property wrappers you need shrink to three:

Swift
// Read-only example: needs SwiftUI.
import SwiftUI
import Observation

@Observable
final class Profile {
    var name = "Ada"
    var avatarURL: URL?
}

struct ProfileScreen: View {
    @State private var profile = Profile()      // this view owns the model

    var body: some View {
        VStack {
            Text(profile.name)                  // tracks `name` only
            NameEditor(profile: profile)
        }
    }
}

struct NameEditor: View {
    @Bindable var profile: Profile              // gives $profile.name

    var body: some View {
        TextField("Name", text: $profile.name)
    }
}
  • @State keeps the model alive for the view's lifetime. It replaces @StateObject.
  • A plain let or var is enough to receive a model that another view owns. No @ObservedObject is needed.
  • @Bindable lets you write $profile.name for two-way controls.
  • @Environment passes a model to a whole subtree: .environment(profile) above and @Environment(Profile.self) var profile below.

The older style used ObservableObject and @Published. Its model announces "something changed" for any published property, so every view using the object redraws. Observation is finer-grained and needs less code.

Design advice

  • Keep models small and focused. One @Observable class per concept (a cart, a profile, a download) is easier to reason about than one huge store.
  • Put @MainActor on a model that views read, and do slow work in a Task (see actors and tasks). Update the model on the main actor.
  • Do not read observed properties in code that runs on every frame unless it must; every read creates a dependency.
  • Writing an equal value to an Equatable property does not notify (unlike didSet, which fires every time), but a property whose type is not Equatable notifies on every write.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @Observable do to the stored properties of a class?

    The macro generates hidden storage and accessors that notify a registrar on every read and write, so tracking is automatic.
  2. 2. A tracking closure reads only score. The code then changes name. What happens?

    Observation records the properties actually read inside the closure and notifies only about those.
  3. 3. How many times does a single withObservationTracking call invoke onChange?

    Tracking is one-shot. Frameworks re-run the reading code, which registers fresh dependencies.
  4. 4. Which attribute keeps a stored property of an @Observable class out of tracking?

    @ObservationIgnored is for caches, loggers and anything that should not trigger updates.
  5. 5. Why can't you apply @Observable to a struct?

    A struct is copied on assignment, so there is no single instance to observe. Use a final class.

Summary

  • @Observable makes a class's stored properties tracked; no @Published wrappers are needed.
  • withObservationTracking runs a closure, records which properties it read, and calls onChange once, before the first of them changes.
  • Tracking is per property and one-shot; frameworks re-run the reading code to re-arm it.
  • Computed properties follow the stored properties they read; @ObservationIgnored opts a property out; nested observable objects compose.
  • Observations { ... } exposes changes as an AsyncSequence and may batch rapid writes.
  • In SwiftUI use @State to own a model, a plain property to receive it, @Bindable for $ bindings and @Environment to share it.

Next: SwiftUI State, Bindings and Layout