How Swift Observation works: the access list behind @Observable, and what Swift 6.2 and 6.4 added
What the @Observable macro generates, how withObservationTracking records property reads, why onChange fires once and early, and how SwiftUI and UIKit use it.
· 10 min read
- Swift
- SwiftUI
- Observation
Since iOS 17, a SwiftUI view that reads model.title in its body updates when title changes and stays put when model.subtitle does. Nothing declares that dependency: no @Published, no objectWillChange, no list of key paths. A macro and a small runtime do it, and once you have seen how, the odd behaviours stop being odd: why withObservationTracking’s onChange fires once and before the value changes, why a let is never tracked, why appending to an array always notifies but assigning an equal string does not, and why a property read inside a List row belongs to the row and not the view that built it.
This article reads the implementation: the @Observable macro and the Observation module at the swift-6.4.3-RELEASE tag (Swift 6.4, the toolchain in Xcode 27), plus the three evolution proposals (SE-0395, SE-0475 and SE-0506) and Apple’s documentation. We could not compile Swift where we wrote this, so the snippets are checked against that source rather than run.
What the macro generates
@Observable only applies to classes; the macro rejects structs, enums and actors with an error. It adds a registrar, a conformance and some helper methods (access, withMutation and, since Swift 6.2, the shouldNotifyObservers overloads), then rewrites every stored instance var that isn’t marked @ObservationIgnored. A let, a static property and a computed property are left alone, so a let or a static is never tracked, and a computed property is tracked only through the stored properties it reads. Trimmed from the macro’s templates (the init accessor and the macro’s unique generic names are omitted), a model like this:
@Observable
final class Basket {
var items: [Item] = []
var note = ""
}
expands to roughly this:
final class Basket {
@ObservationIgnored private let _$observationRegistrar = Observation.ObservationRegistrar()
internal nonisolated func access<M>(keyPath: KeyPath<Basket, M>) {
_$observationRegistrar.access(self, keyPath: keyPath)
}
internal nonisolated func withMutation<M, R>(keyPath: KeyPath<Basket, M>, _ mutation: () throws -> R) rethrows -> R {
try _$observationRegistrar.withMutation(of: self, keyPath: keyPath, mutation)
}
@ObservationIgnored private var _note = ""
var note: String {
get {
access(keyPath: \.note)
return _note
}
set {
guard shouldNotifyObservers(_note, newValue) else { _note = newValue; return }
withMutation(keyPath: \.note) { _note = newValue }
}
_modify {
access(keyPath: \.note)
_$observationRegistrar.willSet(self, keyPath: \.note)
defer { _$observationRegistrar.didSet(self, keyPath: \.note) }
yield &_note
}
}
// items is rewritten the same way
}
extension Basket: nonisolated Observation.Observable {}
The nonisolated on the conformance arrived in Swift 6.2. Three details in that expansion decide behaviour you will meet in practice.
The getter is the whole tracking mechanism. Every read calls access(keyPath:). There is no list of observed properties anywhere; a property is observed because something read it.
The setter skips equal values. Since Swift 6.2 the macro generates four shouldNotifyObservers overloads: lhs != rhs for Equatable values and for Equatable classes, lhs !== rhs for other class references, and true for anything else. Assigning a String equal to the current one stores it and notifies nobody. The comparison still runs, so for a large array it is silent rather than free. Before 6.2 every assignment notified.
In-place mutation always notifies. basket.items.append(item) and basket.note += "!" go through the _modify accessor, which calls willSet and didSet with no equality check. The source has a comment explaining why: comparing a container before and after would make an append O(n) and could force a copy. So basket.items = basket.items is silent if Item is Equatable, while basket.items.sort() on an already sorted array fires. Which accessor a statement uses decides whether anyone hears about it.
How withObservationTracking knows what you read
The entry point everyone else is built on is withObservationTracking(_:onChange:), available since iOS 17. It runs your apply closure, works out which properties it read, and calls onChange when one of them is about to change. The “works out” part is the interesting bit, and it is a thread-local.
Before running apply, the function stores a pointer to an empty, optional access list in thread-local storage (the module has its own _swift_observation_tls_get and _swift_observation_tls_set runtime functions for this), and restores the previous value afterwards. The registrar’s access method, which every getter calls, does this:
// ObservationRegistrar.access(_:keyPath:), trimmed
if let trackingPtr = _ThreadLocal.value?.assumingMemoryBound(to: ObservationTracking._AccessList?.self) {
if trackingPtr.pointee == nil {
trackingPtr.pointee = ObservationTracking._AccessList()
}
trackingPtr.pointee?.addAccess(keyPath: keyPath, context: context)
}
If no tracking is in progress on this thread, the thread-local is nil and the getter costs a thread-local read and a nil check. If one is, the key path is added to the list under the registrar’s identity, so the list ends up as “this object: these key paths; that object: those key paths”.
When apply returns, the function walks the list and registers one observer with each registrar it found, for that registrar’s set of key paths. A registrar keeps its observers in a dictionary from key path to observer ids. The setter’s willSet looks up the key path, takes a copy of the matching observers under the registrar’s lock, releases the lock, and calls each one. For the plain onChange variant, the observer calls your closure and then cancels the whole tracking, removing itself from every registrar it was registered with.
Everything people find surprising about this API follows from that description:
- It fires once. The first
willSeton any tracked property callsonChangeand cancels the tracking. Five properties changing in a row produce one call. To keep observing, register again fromonChange. The SE-0395 example does that from aTask { @MainActor in … }rather than on the spot, and the next bullet is why. - It fires before the change. The hook is
willSet, so reading the property insideonChangegives the old value. SwiftUI only needs to know “something you depend on is invalid” and reads the new values when it next evaluatesbody, so for its purposes early is correct. - It runs on the mutating thread, synchronously, inside the setter. No lock is held while your closure runs, but you are on whichever thread did the write. Hop to the main actor yourself if you need it.
- Only reads on the calling thread, during
apply, count. A closure thatapplystores and something else runs later records nothing for this scope. That is the mechanism behind Apple’sListguidance: aList(books) { book in Text(book.title) }makes the view depend onbooks, and each row depend on its owntitle, because the row closure runs later when the row is created. A nestedwithObservationTrackingmerges its reads into the outer scope’s list as it exits, so wrapping doesn’t hide a dependency. - A computed property is tracked through what it reads.
fullNamereadingfirstNameandlastNameregisters both. A collection registers as one property; its elements are not tracked unless you read their properties, and then it is their registrars that record it.
What SwiftUI and UIKit do with it
The doc-comment example on withObservationTracking prints “Schedule renderer.” from onChange, and that is evidently how SwiftUI uses it: body runs inside tracking and the callback marks the view for re-evaluation. Apple’s documentation is explicit that a view forms a dependency only on the properties body actually reads, that reading nothing means never updating, and that an observable object can pass through several view layers without the intermediate views depending on it. The module’s source carries SPI entry points for SwiftUI that expose the willSet and didSet sides separately, which the public API did not until Swift 6.4.
UIKit joined in iOS 18, behind the UIObservationTrackingEnabled Info.plist key, and in iOS 26 it is on by default. UIKit runs a tracking scope around specific methods and re-runs the method when a property read inside it changes. Apple’s list includes layoutSubviews(), updateConstraints() and draw(_:) on views, viewWillLayoutSubviews() and viewDidLayoutSubviews() on controllers, cell and button configuration update handlers, and the new updateProperties() on both UIView and UIViewController. Apple describes the update pass as traits first, then updateProperties(), then layoutSubviews(), then display, so updateProperties() is where content and styling go:
@Observable
final class InboxModel {
var unread = 0
var statusText = ""
}
final class InboxViewController: UIViewController {
let model: InboxModel
let statusLabel = UILabel()
/* … */
override func updateProperties() {
super.updateProperties()
statusLabel.text = model.statusText // tracked
statusLabel.isHidden = model.unread == 0 // tracked
}
}
When statusText changes, UIKit calls updateProperties() again on the next update pass. You don’t call setNeedsLayout(); the tracking re-runs this method, not your layoutSubviews() override. Whether a layout pass follows depends on what you set: a label whose text changes still invalidates its intrinsic content size. For state that isn’t observable, setNeedsUpdateProperties() schedules the pass by hand.
Observations: changes as an async sequence (Swift 6.2, iOS 26)
withObservationTracking is awkward outside a UI framework: you re-register in every callback, you get the old value, and you are on the wrong thread. SE-0475 added Observations, an AsyncSequence built on the same tracking, available from iOS 26 and macOS 26:
@Observable
final class Person {
var firstName = ""
var lastName = ""
var name: String { firstName + " " + lastName }
}
@MainActor
func watch(_ person: Person) -> Task<Void, Never> {
let names = Observations { person.name } // closure inherits @MainActor
return Task {
for await name in names {
print(name)
}
}
}
The closure is @isolated(any) and inherits the actor context where the sequence is created, so here it always runs on the main actor, and Person doesn’t need to be Sendable. The first call to next() runs the closure inside withObservationTracking on that isolation and returns the value. After that each next() waits for a willSet on any property the closure read, then hops back to the closure’s isolation and runs it again.
That second hop is what makes the sequence transactional. The mutating code is on the main actor and holds it until it suspends, so the closure cannot run between person.firstName = "Jane" and person.lastName = "Appleseed". You see “Jane Appleseed”, never a torn “Jane “ with the old surname. Several synchronous writes become one element. There is no buffer: a consumer slower than the producer gets the latest value when it next asks and misses the intermediate ones, which for model state is what you want. The sequence ends when the task is cancelled, when the closure throws, or when a closure passed to Observations.untilFinished returns .finish (the proposal text says .finished; the shipped case is .finish).
Swift 6.4: didSet, deinit and continuous observation (iOS 27)
SE-0506, implemented in Swift 6.4 and available from iOS 27 and macOS 27, exposes the sides of the mechanism that SwiftUI had through SPI. withObservationTracking(options:_:onChange:) takes a set of .willSet, .didSet and .deinit, and hands onChange an event you can ask about:
withObservationTracking(options: [.didSet, .deinit]) {
_ = basket.items
_ = basket.note
} onChange: { event in
switch event.kind {
case .didSet:
if event.matches(\Basket.items) { /* new value is stored now */ }
case .deinit:
/* the basket is going away */
default:
break
}
}
With .didSet the callback arrives after the store, so reading the property gives the new value. With .deinit you hear when a tracked object is going away, which an observer holding a weak reference previously had to poll for. The proposal notes that weak references to it are already nil when the event arrives, but the object may not have finished deinitialising. event.cancel() stops further events, and if you cancel in a willSet event the matching didSet never comes.
The same proposal adds a continuous variant, for code that wants the Observations behaviour as a callback rather than a loop. Note the name: the proposal calls it withContinuousObservationTracking, but the function that shipped in 6.4 and in Apple’s documentation is withContinuousObservation(options:apply:):
@MainActor
final class StatusController {
let model: InboxModel
let label: UILabel
let observation: ObservationTracking.Token
init(model: InboxModel, label: UILabel) {
self.model = model
self.label = label
observation = withContinuousObservation(options: [.willSet]) { [model, label] event in
label.text = model.statusText
}
}
}
The closure runs on the creating isolation and asynchronously, even the first time: once with an .initial event, then after each change at the next suspension point, so it coalesces writes the same way Observations does. That is also why .willSet is enough here: the closure runs after the write regardless, so it reads the new value, and .didSet would only add a second event per write. It keeps running while the token is alive. Drop the token, or call cancel() on it, and the observation stops.
Rules that follow
- Make value types
Equatableif you want redundant assignments to be silent; mutate in place if you need every mutation to fire. - Treat the plain
onChangeas an invalidation signal: one shot, old value, arbitrary thread. For values, useObservationsor the.didSetoption. - Check your deployment target.
Observationsneeds iOS 26; the options and continuous variants need iOS 27.
The generated access and withMutation helpers are nonisolated, so tracking works wherever the read happens, including under the new default main actor isolation. If you are moving an app to those defaults, our article on default main actor isolation in an existing app covers what does change. For help building or modernising an app on SwiftUI and Observation, see our iOS app development service.