Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 46 ยท State and Data Flow

@Observable and Observation

Share model data across SwiftUI views with the @Observable macro. Learn @State ownership, @Bindable, @Environment, when views re-render, and how to migrate from ObservableObject.

@State is perfect for a toggle or a text field, but real apps have richer data: a shopping cart, a profile, a playlist, a list of tasks with business rules. That data is usually a class with several properties and methods, shared by many views. SwiftUI's modern answer, available from iOS 17, is the @Observable macro from Swift's Observation framework.

You mark a model class @Observable, and SwiftUI automatically notices which properties each view's body reads. When one of those properties changes, only the views that read it are updated. There is no @Published, no objectWillChange, and no manual subscription. This lesson shows how to declare and own models, pass them down, bind to their properties, and migrate older ObservableObject code. It builds on @State and @Binding.

The Observation recipe

@Observable Mark a class as a model.
@State The view that creates the model owns it.
@Bindable Get $ bindings to a model's properties.
@Environment Share a model with a whole subtree.
1 / 2

Declaring a model

Swift
import Observation

@Observable
final class ShoppingCart {
    var items: [String] = []
    var couponCode = ""
    var itemCount: Int { items.count }

    func add(_ item: String) {
        items.append(item)
    }
}

The macro rewrites the stored properties so that reads and writes go through an observation registrar. You write ordinary var properties. Computed properties like itemCount work too, because they read the stored property items, and that read is what gets tracked. Mark a property with @ObservationIgnored if changes to it should never trigger updates, for example a cache or a logger.

Models must be classes: the point is shared identity, many views seeing the same object. For plain values that are copied, a struct with @State remains the right choice.

Owning and passing a model

The view that creates a model owns it with @State, exactly like any other state:

Swift
struct StoreView: View {
    @State private var cart = ShoppingCart()

    var body: some View {
        VStack {
            Text("Items: \(cart.itemCount)")
            Button("Add apple") { cart.add("Apple") }
            CartSummary(cart: cart)
        }
    }
}

struct CartSummary: View {
    let cart: ShoppingCart

    var body: some View {
        Text(cart.items.joined(separator: ", "))
    }
}

CartSummary receives the cart as a plain let. It does not need any wrapper to stay up to date: because its body reads cart.items, Observation tracks that read, and the summary re-renders when the items change. The wrapper is only needed to own the object (@State) or to bind to its properties (@Bindable).

One detail to know: because @State private var cart = ShoppingCart() is a property initializer, keep creating the model cheap and free of side effects. SwiftUI keeps the first instance, but the expression can be evaluated again whenever the owning view struct is re-created.

@Bindable: bindings to properties

A TextField needs a Binding<String>. If the model arrives as a plain property, there is no $ available. Wrap it with @Bindable, which provides bindings to every property of the observable object:

Swift
struct CouponField: View {
    @Bindable var cart: ShoppingCart

    var body: some View {
        TextField("Coupon code", text: $cart.couponCode)
    }
}

If the model is owned with @State in the same view, $cart.couponCode already works. For an object you got from an @Environment property, create the bindable inside body:

Swift
struct CouponFieldFromEnvironment: View {
    @Environment(ShoppingCart.self) private var cart

    var body: some View {
        @Bindable var cart = cart
        TextField("Coupon code", text: $cart.couponCode)
    }
}

@Environment: sharing with a subtree

Passing the same model through five levels of views is tedious. Put it in the environment once, near the top, and read it wherever it is needed:

Swift
@main
struct ShopApp: App {
    @State private var cart = ShoppingCart()

    var body: some Scene {
        WindowGroup {
            StoreView()
                .environment(cart)
        }
    }
}

Any descendant can then declare @Environment(ShoppingCart.self) private var cart. If no one has injected a cart, reading it traps at runtime, so inject it before any view that needs it, including in previews. A later lesson covers the environment and dependency injection in depth.

What triggers a re-render

The rule is simple and worth memorizing: a view updates when a property it read during its last body evaluation changes. Reading cart.itemCount registers items. Setting cart.couponCode does not touch that view, so it is skipped. With the older ObservableObject, any @Published change refreshed every view observing the object, whether it used that property or not.

SwiftUI's own tracking is built on a public tool you can call yourself: withObservationTracking. The first example uses the real macro and function (Swift's Observation framework runs on this site's Swift runner) to show that only a property that was read causes a notification.

Swift Only read properties notify

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.

Notice that onChange fires on the first change to a tracked property, and only once per call. SwiftUI re-runs body and starts tracking again, which is how it keeps following the properties. The second example plays that game with three small stand-in "views" that re-render when marked dirty. The tracking is real; the view class and the flush step are a simplified stand-in (SwiftUI schedules updates itself and coalesces them).

Swift Three stand-in views and one model

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.

NameView re-rendered only when the name changed, CityView only for the city, and the summary for both. Changing visits woke nobody.

Migrating from ObservableObject

Code written before iOS 17 uses Combine-based ObservableObject. It still works, and you need it if you support iOS 16 or earlier. The migration is mostly deletion:

Before (ObservableObject) After (Observation)
class Model: ObservableObject @Observable class Model
@Published var x var x
@StateObject var model = Model() @State var model = Model()
@ObservedObject var model: Model var model: Model (or @Bindable var model: Model for $ bindings)
@EnvironmentObject var model: Model @Environment(Model.self) var model
.environmentObject(model) .environment(model)

Remember the behavioural change: with ObservableObject, a change to any published property invalidates all views that observe the object. With Observation, views update only for the properties they actually read. That usually means fewer redraws, but it also means a property you read outside body (for example in an init) will not be tracked.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement about @Observable is correct?

    The macro is for classes. It rewrites stored properties so reads and writes are observed, with no @Published needed.
  2. 2. A view's body reads only cart.items. The model's couponCode changes. What happens?

    Observation tracks property reads during body. A change to an unread property does not invalidate the view.
  3. 3. When do you need @Bindable?

    @Bindable provides binding syntax such as $cart.couponCode for controls like TextField.
  4. 4. What replaces @StateObject in the Observation world?

    The view that creates an @Observable model owns it with @State. @StateObject belongs to ObservableObject.

Summary

  • @Observable turns a class into a model whose property reads and writes are tracked; no @Published is needed.
  • The creating view owns the model with @State; other views take it as a plain property.
  • @Bindable gives $ bindings to a model's properties; @Environment(Type.self) shares a model with a subtree.
  • A view updates only when a property it read during body changes.
  • Migrating from ObservableObject means removing @Published and swapping @StateObject, @ObservedObject and @EnvironmentObject for @State, plain properties and @Environment.

Next, decide which wrapper fits which job in Choosing the Right Property Wrapper.