What if you never had to pass data by hand again, and your app just updated everywhere automatically?
Why @EnvironmentObject for shared state in iOS Swift? - Purpose & Use Cases
Imagine you have a shopping app where many screens need to know the user's cart items. Without a shared way, you pass the cart data manually from one screen to another.
This feels like handing a heavy box from friend to friend across a long line.
Passing data manually is slow and error-prone. If you forget to pass the cart to a screen, that screen shows wrong or empty info.
Updating the cart means changing code in many places, which is tiring and causes bugs.
@EnvironmentObject lets you share data easily across many screens without passing it manually. It acts like a shared backpack everyone can reach anytime.
This keeps your app clean and updates happen everywhere automatically when data changes.
struct ScreenA: View {
var cart: Cart
var body: some View { NavigationLink(destination: ScreenB(cart: cart)) { Text("Go") } }
}
struct ScreenB: View {
var cart: Cart
var body: some View { Text("Items: \(cart.items.count)") }
}class Cart: ObservableObject { @Published var items = [String]() } struct ScreenA: View { @EnvironmentObject var cart: Cart var body: some View { NavigationLink(destination: ScreenB()) { Text("Go") } } } struct ScreenB: View { @EnvironmentObject var cart: Cart var body: some View { Text("Items: \(cart.items.count)") } }
You can build apps where many parts share and react to data changes instantly, without messy code or bugs.
In a social media app, the user profile info is shared across many screens. Using @EnvironmentObject, when the user updates their name, all screens show the new name immediately.
Passing shared data manually is hard and error-prone.
@EnvironmentObject provides a simple, automatic way to share state across views.
This makes your app easier to build, maintain, and update.