Files
swift-mirror/stdlib/stdlib.docc/Observation/Observation-collection.md
T
Graham Lee 9ead8781d4 Add .docc catalog to publish stdlib docs on swift.org
Co-authored-by: Alex Martini <amartini@apple.com>
Co-authored-by: Graham Lee <glee23@apple.com>
Co-authored-by: Chris Adamson <cadamson@apple.com>
Co-authored-by: Kirby Turner <kirby_turner@apple.com>
Co-authored-by: Paris Pinkney <ppinkney@apple.com>
Co-authored-by: Dave Spector <dspector@apple.com>
Co-authored-by: Sofia Rodriguez Morales <sofia_rodriguez@apple.com>
Co-authored-by: Ethan Kusters <ekusters@apple.com>
Co-authored-by: Goli Mohammadi <g_mohammadi@apple.com>
Co-authored-by: Adora Vaz <a_vaz@apple.com>
Co-authored-by: David Rönnqvist <ronnqvist@apple.com>
Co-authored-by: Nate Merseth Cook <natecook@apple.com>
Co-authored-by: Susan Conant <susan_c@apple.com>
2026-04-10 10:04:56 -04:00

2.1 KiB

Observation

Make responsive apps that update the presentation when underlying data changes.

Overview

Observation provides a robust, type-safe, and performant implementation of the observer design pattern in Swift. This pattern allows an observable object to maintain a list of observers and notify them of specific or general state changes. This has the advantages of not directly coupling objects together and allowing implicit distribution of updates across potential multiple observers.

The Observation frameworks provides the following capabilities:

  • Marking a type as observable
  • Tracking changes within an instance of an observable type
  • Observing and utilizing those changes elsewhere, such as in an app's user interface

To declare a type as observable, attach the Observation/Observable() macro to the type declaration. This macro declares and implements conformance to the Observation/Observable protocol to the type at compile time.

@Observable
class Car {
    var name: String = ""
    var needsRepairs: Bool = false
    
    init(name: String, needsRepairs: Bool = false) {
        self.name = name
        self.needsRepairs = needsRepairs
    }
}

To track changes, use the Observation/withObservationTracking(_:onChange:) function. For example, in the following code, the function calls the onChange closure when a car's name changes. However, it doesn't call the closure when a car's needsRepair flag changes. That's because the function only tracks properties read in its apply closure, and the closure doesn't read the needsRepair property.

func render() {
    withObservationTracking {
        for car in cars {
            print(car.name)
        }
    } onChange: {
        print("Schedule renderer.")
    }
}

Topics

Observable conformance

  • Observation/Observable()
  • Observation/Observable

Fine-tuning

  • Observation/ObservationIgnored()
  • Observation/ObservationTracked()

Change tracking

  • Observation/withObservationTracking(_:onChange:)
  • Observation/ObservationRegistrar