How do you share state between SwiftUI views with the environment?

← Swift answers

Create the model once near the top of the view tree, inject it with .environment (for @Observable) or .environmentObject, and read it in any child view.

With the Observation framework (iOS 17 and later), mark the model @Observable and inject it by type:

@Observable
final class Session {
    var userName = "Guest"
}
 
@main
struct DemoApp: App {
    @State private var session = Session()
 
    var body: some Scene {
        WindowGroup {
            ContentView().environment(session)
        }
    }
}
 
struct ContentView: View {
    @Environment(Session.self) private var session
 
    var body: some View {
        Text("Hello, \(session.userName)")
    }
}

For earlier iOS versions, make the model an ObservableObject with @Published properties, inject it with .environmentObject(session) and read it with @EnvironmentObject. A view that reads an object nobody injected crashes at runtime, so inject it above every view that needs it, including previews and sheets.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required