@Observable in SwiftUI: data flow explained simply

Since iOS 17, @Observable replaces the old ObservableObject approach. What changes, and when to use @State, @Bindable and @Environment.

1 min readby Luca Ring

Passing data cleanly through a SwiftUI app used to be confusing: ObservableObject, @Published, @StateObject, @ObservedObject, @EnvironmentObject. Since iOS 17, the Observation framework offers a much simpler way. If you start a new app today, it's the right choice.

Before and after

You used to mark every property that should update the interface with @Published. With the @Observable macro, SwiftUI automatically tracks exactly the properties a view actually reads:

import Observation

@Observable
final class Journal {
    var entries: [Entry] = []
    var searchText = ""
}

That has a nice side effect: when searchText changes, only the views that display searchText get redrawn. Apps feel noticeably smoother.

The three tools you need

  • @State holds an object owned by the view. It replaces @StateObject.
  • @Bindable creates bindings to properties of an observed object, for example for a TextField.
  • @Environment passes an object down the whole hierarchy. It replaces @EnvironmentObject.
@main
struct MyApp: App {
    @State private var journal = Journal()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(journal)
        }
    }
}

struct SearchField: View {
    @Environment(Journal.self) private var journal

    var body: some View {
        @Bindable var journal = journal
        TextField("Search", text: $journal.searchText)
    }
}

Common pitfalls

  • Classes, not structs: @Observable only works with classes. For simple values, @State with a struct is still ideal.
  • No more @ObservedObject: when you pass an observed object to a subview, a plain let or var is enough.
  • Don't observe everything: mark properties that don't affect the interface with @ObservationIgnored.

And data on disk?

@Observable handles state in memory. If data should be stored permanently, SwiftData is the next step, and the nice part is that SwiftData models are observable automatically. How to get started is covered in SwiftData: first steps.

  • Observable
  • SwiftUI
  • State
  • Bindable
  • Observation framework