---
title: "How do you share state between SwiftUI views with the environment?"
description: "Inject a shared model with .environment (Observable) or .environmentObject, then read it in child views without passing it through every initializer."
url: "https://bugsee.com/answers/swift/share-state-with-environmentobject/"
---

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

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:

```swift
@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

- [How do you dismiss the keyboard in SwiftUI?](https://bugsee.com/answers/swift/dismiss-the-keyboard-in-swiftui/)
- [How do you fix "Unexpectedly found nil while unwrapping an Optional value"?](https://bugsee.com/answers/swift/unexpectedly-found-nil-while-unwrapping-optional/)
