Observation and @Observable
suggest changeOften one part of a program needs to know when data in another part changes: a view has to redraw when a model changes, or a cache has to be cleared when settings change. Swift has had several ways to do this: property observers (willSet / didSet), NotificationCenter (see Observer), Key-Value Observing (KVO) from Objective-C, Combine's ObservableObject with @Published, and libraries like RxSwift.
Swift 5.9 added the Observation module (SE-0395). It is part of the standard toolchain, so it works on Linux and Windows too, not just on Apple platforms. It has three parts:
- the
@Observablemacro, which makes the stored properties of a class observable withObservationTracking(_:onChange:), which records which properties a closure reads and tells you once when one of them is about to changeObservations(Swift 6.2, SE-0475), anAsyncSequencethat gives you a new value each time the observed properties change
You don't subscribe to individual properties. You run some code, Observation records every observable property it reads, and that set of properties is what you're watching. SwiftUI is built on this: a view's body is the code that runs, so the view redraws only when a property it actually read changes.
The examples were compiled and run with Swift 6.4.1 on Windows, in the Swift 6 language mode:
swiftc -swift-version 6 main.swift -o main.exe
The SwiftUI and Combine examples near the end need Apple platforms and were not run.
A first @Observable class
Put @Observable on a class and import Observation:
import Observation
@Observable
final class Player {
var name: String
var score = 0
var lives = 3
init(name: String) {
self.name = name
}
}
let player = Player(name: "Ada")
withObservationTracking {
print("render: \(player.name) has \(player.score) points")
} onChange: {
print("onChange: something the closure read will change")
}
player.lives -= 1 // not read in the tracking closure: no callback
player.score += 10 // triggers onChange once
player.score += 10 // already fired: no callback
print("final score:", player.score)
render: Ada has 0 points
onChange: something the closure read will change
final score: 20
What happened:
withObservationTrackingruns the first closure right away and records that it readnameandscoreonplayer.liveswas not read, so changing it doesn't trigger anything.- The first change to
scorecallsonChange. - Tracking is one-shot. After
onChangehas run, the observation is gone, and the second change toscoreis not reported. To keep watching, you register again (shown below), or useObservations.
@Observable doesn't change how you write or use the class. Properties are ordinary vars and the initializer is ordinary code. The macro turns each stored var into a computed property that tells an ObservationRegistrar about every read and write. The Macros article shows the full expansion. In short, @Observable adds:
- a private
_$observationRegistrarproperty access(keyPath:)andwithMutation(keyPath:_:)helper methods- for each stored
var x, a hidden_xproperty, plus a getter and setter forxthat call those helpers - a conformance to the
Observableprotocol, which is only a marker and has no requirements
What gets tracked
Only properties read while the tracking closure runs are tracked. Reads through computed properties count, because a computed property reads stored properties. @ObservationIgnored turns tracking off for one property:
import Observation
@Observable
final class Cart {
var items: [String] = []
var discount = 0.0
@ObservationIgnored var lastSaved = "never"
var count: Int { items.count } // computed: reads `items`
}
@MainActor
func observe<T>(_ label: String, _ read: () -> T) {
let value = withObservationTracking {
read()
} onChange: {
print(" \(label) will change")
}
print("\(label) = \(value)")
}
let cart = Cart()
observe("count") { cart.count }
observe("lastSaved") { cart.lastSaved }
print("set lastSaved")
cart.lastSaved = "12:00"
print("set discount")
cart.discount = 0.1
print("append item")
cart.items.append("apple")
print("append another")
cart.items.append("pear")
count = 0
lastSaved = never
set lastSaved
set discount
append item
count will change
append another
withObservationTrackingreturns whatever the first closure returns, so you can use it as an expression.- Reading
counttrackeditems, the stored property behind it. - The
lastSavedobserver never fires. An ignored property is a plain stored property, and reading it records nothing. discountwasn't read, so changing it doesn't notify anyone.- The second append is not reported, because the observation was already used up.
Tracking works per property, not per object. It's also dynamic: if the closure reads a only when b is true, then a is tracked only on runs where b was true.
Use @ObservationIgnored for caches, loggers, delegates and anything else that views or other observers should not react to.
Nested observable objects
Tracking follows the reads into other observable objects. Here remaining reads the array of items and the done property of each item:
import Observation
@Observable
final class TodoItem {
var title: String
var done = false
init(_ title: String) { self.title = title }
}
@Observable
final class TodoList {
var items: [TodoItem] = []
var remaining: Int { items.filter { !$0.done }.count }
}
let list = TodoList()
list.items = [TodoItem("write"), TodoItem("test"), TodoItem("ship")]
@MainActor func watchRemaining() {
let n = withObservationTracking {
list.remaining
} onChange: {
print(" remaining will change")
}
print("remaining:", n)
}
watchRemaining()
print("mark first done")
list.items[0].done = true
watchRemaining()
print("rename second")
list.items[1].title = "test it"
print("append")
list.items.append(TodoItem("celebrate"))
remaining: 3
mark first done
remaining will change
remaining: 2
rename second
append
remaining will change
Changing done on one item is reported, because remaining read it. Renaming an item is not, because no one read title. With ObservableObject this was hard to do: a change inside a nested object did not update a view that observed the parent object.
Setting the same value
For Equatable properties, the generated setter skips the notification when the new value equals the old one:
import Observation
@Observable
final class Settings {
var theme = "light"
var fontSize = 14
}
let settings = Settings()
@MainActor func watch(_ label: String) {
withObservationTracking {
_ = settings.theme
} onChange: {
print(" \(label): theme will change")
}
}
watch("A")
print("set theme = light (same value)")
settings.theme = "light"
print("set theme = dark")
settings.theme = "dark"
set theme = light (same value)
set theme = dark
A: theme will change
You can see this check in the macro expansion: the setter calls shouldNotifyObservers(_theme, newValue) before withMutation. For types that aren't Equatable, every assignment notifies. For classes, the check compares identity (===).
onChange runs before the change, and is @Sendable
Two details of onChange surprise people:
- It's called synchronously from inside the setter, before the new value is stored. It works like
willSet, notdidSet. If you read the property inonChange, you get the old value. - The closure is
@Sendable. It can be called from whatever thread made the change, so the compiler doesn't let it capture non-Sendablestate.
The second point shows up as soon as you try to read the model in onChange in Swift 6 mode. In top-level code, globals are isolated to the main actor:
withObservationTracking {
print("render: \(player.name) has \(player.score) points")
} onChange: {
print("onChange: score is still \(player.score)")
}
main.swift:19:39: error: main actor-isolated let 'player' can not be referenced from a nonisolated context
An @Observable class is not Sendable by itself: it's a class with mutable state. The usual fix in app code is to isolate the model to the main actor. A @MainActor class is Sendable, all its properties are only touched on the main thread, and onChange is then called on the main thread too. To keep observing, onChange registers again in a new Task, which runs after the setter finishes and the new value is stored:
import Observation
@MainActor
@Observable
final class Thermostat {
var celsius = 20.0
}
@MainActor
func track(_ t: Thermostat) {
withObservationTracking {
print("showing \(t.celsius)°C")
} onChange: {
// Runs synchronously inside the setter, before the new value is stored.
MainActor.assumeIsolated {
print("about to change, still \(t.celsius)°C")
}
Task { @MainActor in
track(t) // re-register; by now the new value is stored
}
}
}
let t = Thermostat()
track(t)
t.celsius = 21.5
await Task.yield()
t.celsius = 23
t.celsius = 24 // second change before the Task re-registered
await Task.yield()
try await Task.sleep(for: .milliseconds(50))
showing 20.0°C
about to change, still 20.0°C
showing 21.5°C
about to change, still 21.5°C
showing 24.0°C
MainActor.assumeIsolatedis needed becauseonChangeis declared as nonisolated. It checks at run time that we really are on the main thread, and crashes if not. That's safe here because every write to a@MainActormodel happens on the main actor.- The changes to 23 and 24 happen with no suspension point between them. The first one fires
onChange. The second one happens beforetrackregistered again, so nobody sees 23. This is the behavior you usually want for UI: redraw once with the latest state, not once per assignment. SwiftUI works the same way.
Writing this re-registration loop by hand is tedious and easy to get wrong. Since Swift 6.2 there's a better way.
The Observations async sequence (Swift 6.2)
Observations wraps the "track, wait for a change, track again" loop in an AsyncSequence. You give it a closure that reads observable properties and returns a value. It yields the current value right away, and a new value after each change:
import Observation
@Observable
final class Counter {
var value = 0
}
let counter = Counter()
let task = Task {
for await v in Observations({ counter.value }) {
print("observed", v)
if v >= 3 { break }
}
print("loop ended")
}
try await Task.sleep(for: .milliseconds(50))
counter.value = 1
try await Task.sleep(for: .milliseconds(50))
counter.value = 2 // two changes with no suspension in between
counter.value = 3
await task.value
observed 0
observed 1
observed 3
loop ended
How Observations behaves:
- The first value is yielded right away. You don't need to read the initial state separately.
- Values are yielded after the change. Unlike
onChange, you get the new value. - Changes are grouped into transactions. When a property changes, the sequence waits until the code making the change reaches its next suspension point (an
await), then runs the closure once.value = 2followed directly byvalue = 3is one transaction, so you see only 3. - It doesn't buffer. A slow consumer gets the latest value when it asks for the next one, not every value in between.
- The closure is
@isolated(any). It runs on the actor it was written in. Here that's the main actor, the same actor that ownscounter, so it can read the global safely. - Breaking out of the loop, or cancelling the task, ends the observation.
Because the element type can be anything Sendable, the closure can read several properties and combine them into one value. In this example the closure reads unread only when someone is signed in, and the set of tracked properties changes with each run:
import Observation
@MainActor
@Observable
final class Session {
var user: String?
var unread = 0
}
@MainActor
func run() async {
let session = Session()
let badge = Task {
// The closure runs on the main actor, like `session`.
let values = Observations {
if let user = session.user { "\(user): \(session.unread) unread" } else { "signed out" }
}
var signedIn = false
for await text in values {
print("badge:", text)
if text == "signed out" && signedIn { break }
signedIn = text != "signed out"
}
}
await Task.yield()
session.user = "ada"
await Task.yield()
session.unread = 3
await Task.yield()
session.user = nil
await badge.value
}
await run()
badge: signed out
badge: ada: 0 unread
badge: ada: 3 unread
badge: signed out
Ending the sequence: untilFinished
A plain Observations sequence never ends by itself. Observations.untilFinished takes a closure that returns .next(value) to yield a value, or .finish to end the sequence:
import Observation
@Observable
final class Download {
var name: String
var received = 0
var total: Int
init(name: String, total: Int) {
self.name = name
self.total = total
}
}
let download = Download(name: "swift.zip", total: 400)
let watcher = Task {
let updates = Observations<String, Never>.untilFinished {
if download.received >= download.total { return .finish }
let percent = download.received * 100 / download.total
return .next("\(download.name): \(percent)%")
}
for await line in updates {
print(line)
}
print("download complete")
}
for _ in 0..<4 {
try await Task.sleep(for: .milliseconds(30))
download.received += 100
}
await watcher.value
swift.zip: 0%
swift.zip: 25%
swift.zip: 50%
swift.zip: 75%
download complete
The compiler can't infer the element type from a multi-statement closure, so it's spelled out: Observations<String, Never>. The second generic parameter is the failure type. With a throwing closure, use Observations<T, any Error> and for try await.
On Apple platforms, Observations requires macOS 26, iOS 26 or later, because the Observation module ships with the OS there. With older deployment targets, use withObservationTracking.
Rules and pitfalls
Only classes
@Observable needs reference semantics, because observers hold on to one shared instance:
@Observable
struct Point {
var x = 0
}
main.swift:3:1: error: '@Observable' cannot be applied to struct type 'Point' (from macro 'Observable')
Actors aren't supported either. The class doesn't have to be final, and an observable class can be a subclass.
let and lazy
A let property is left alone. It can't change, so there's nothing to observe. lazy var fails with a pile of macro errors ('lazy' cannot be used on a computed property), because the macro turns every stored var into a computed one. Mark lazy properties @ObservationIgnored:
import Observation
@Observable
final class Report {
let id: Int
@ObservationIgnored lazy var header = makeHeader()
var rows: [String] = []
init(id: Int) { self.id = id }
private func makeHeader() -> String {
print("building header")
return "Report #\(id)"
}
}
let r = Report(id: 7)
print(r.header)
print(r.header)
building header
Report #7
Report #7
Property wrappers
A property wrapper on a tracked property doesn't work either. Both the wrapper and the macro want to create a backing property named _level:
error: invalid redeclaration of synthesized property '_level'
error: property wrapper cannot be applied to a computed property
The way around it is to hide the wrapped storage with @ObservationIgnored, and write a computed property that reports reads and writes with the access(keyPath:) and withMutation(keyPath:_:) helpers that @Observable generates. That's the same code the macro writes for a normal property:
import Observation
@propertyWrapper
struct Clamped {
private var value: Int
let range: ClosedRange<Int>
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
}
@Observable
final class Speaker {
// Wrapped storage, hidden from the macro.
@ObservationIgnored @Clamped(0...100) private var storedVolume = 50
// Tracked by hand with the helpers @Observable generates.
var volume: Int {
get {
access(keyPath: \.volume)
return storedVolume
}
set {
withMutation(keyPath: \.volume) {
storedVolume = newValue
}
}
}
// didSet works on tracked properties, for side effects.
var balance = 0 {
didSet { print(" balance changed from \(oldValue) to \(balance)") }
}
}
let speaker = Speaker()
withObservationTracking {
print("volume", speaker.volume, "balance", speaker.balance)
} onChange: {
print("speaker will change")
}
speaker.volume = 250
print("volume", speaker.volume)
speaker.balance = -4
volume 50 balance 0
speaker will change
volume 100
balance changed from 0 to -4
Don't assign to a property in its own didSet
willSet and didSet work on tracked properties, as balance shows. But in a plain class you can fix up a value in its own didSet, and in an @Observable class you can't:
@Observable
final class Speaker {
var balance = 0 {
didSet { balance = min(max(balance, -10), 10) }
}
}
let speaker = Speaker()
speaker.balance = -40
*** Program crashed: Stack overflow at 0x00007ffac4b988e6 ***
In a plain class, assigning to a property inside its own didSet sets the storage directly. After the macro runs, balance is a computed property, so the assignment calls the setter again, which calls didSet again, until the stack overflows. Clamp in a computed property, as with volume above, or validate before you assign.
Threads
The registrar is thread-safe, but your class isn't. The macro doesn't make the class Sendable, and it doesn't stop two threads from writing the same property at once. Isolate models to an actor, usually @MainActor for anything UI-related (see Actors and Sendable and Swift 6 data-race safety), and the compiler will check how they're used.
Replacing ObservableObject and KVO
Before Observation, SwiftUI models used Combine. This code needs Apple platforms and was not run:
// Before: Combine (Apple platforms only, not run)
import Combine
final class ProfileModel: ObservableObject {
@Published var name = ""
@Published var followers = 0
var cache: [String: String] = [:] // not @Published
}
// After: Observation
import Observation
@Observable
final class ProfileModel {
var name = ""
var followers = 0
@ObservationIgnored var cache: [String: String] = [:]
}
The differences:
ObservableObject + @Published |
@Observable |
|
|---|---|---|
| What you mark | each observed property (opt in) | the class; opt out with @ObservationIgnored |
| Granularity | the whole object: any @Published change notifies every subscriber |
per property that was actually read |
| Nested objects | changes inside a child object aren't seen | tracked through every read |
| Optionals and arrays of models | need extra work | just work |
| Platforms | Apple (Combine) | any Swift platform |
| Change stream | objectWillChange, $name publisher |
withObservationTracking, Observations |
KVO (@objc dynamic var, observe(\.name)) needs an NSObject subclass and the Objective-C runtime, so it exists only on Apple platforms. Observation does the same job for plain Swift classes and works everywhere.
SwiftUI note
SwiftUI (iOS 17, macOS 14 and later) tracks every observable property a view's body reads and redraws only that view when one changes. You use @State instead of @StateObject to own a model, plain properties or @Environment instead of @ObservedObject / @EnvironmentObject, and @Bindable to create bindings. This code needs Apple platforms and was not run:
// SwiftUI (Apple platforms only, not run)
import SwiftUI
struct ProfileView: View {
@State private var model = ProfileModel() // was @StateObject
var body: some View {
VStack {
Text(model.name) // body depends on `name` only
EditName(model: model)
}
.environment(model) // was .environmentObject(model)
}
}
struct EditName: View {
@Bindable var model: ProfileModel // was @ObservedObject
var body: some View {
TextField("Name", text: $model.name) // a Binding into the model
}
}
struct FollowerCount: View {
@Environment(ProfileModel.self) private var model // was @EnvironmentObject
var body: some View {
Text("\(model.followers) followers")
}
}
ProfileView redraws when name changes but not when followers changes, because its body never read followers. With ObservableObject, any @Published change would redraw every view that observes the model.
Summary
@Observableon a class makes its storedvars observable. It's a macro, so the class still looks and behaves like a normal class.- Observation tracks the properties you read, not properties you name. Reads through computed properties and nested observable objects count.
withObservationTracking { read } onChange: { }fires once, before the change, in a@Sendableclosure. Register again to keep watching.Observations { ... }(Swift 6.2) is anAsyncSequencethat yields the current value and then the new value after each transaction. UseObservations.untilFinishedto end it from inside.@ObservationIgnoredopts a property out. It's required forlazyproperties and properties with property wrappers.- Assigning the same value to an
Equatableproperty doesn't notify. Assigning to a property in its owndidSetoverflows the stack. - Structs and actors can't be
@Observable. For thread safety, isolate models to an actor, usually@MainActor.