In SwiftUI, a cart screen stores its @Observable model as a plain property initialized inline and loses the items whenever its parent redraws; why, and how should the model be owned and shared?
answer
- view structs are rebuilt often
- storage that outlives the struct
- one owner, many readers
- lookup by type in the environment
basics
~20 sA plain property initialized inline is re-created every time the parent rebuilds the view, so a fresh empty CartModel replaces the old one. Own the model with @State where it is created, pass it down, or place it with environment(_:).
solid answer
~50 sView structs are cheap values that SwiftUI rebuilds whenever a parent's `body` runs, so `var cart = CartModel()` makes a new, empty cart each time. `@State private var cart = CartModel()` tells SwiftUI to keep the instance for the view's lifetime. Children receive the model as a plain property, or `@Bindable` when they need bindings, never as their own `@State`. To reach a tab badge and a checkout button far apart, I call `.environment(cart)` on an ancestor and read it with `@Environment(CartModel.self) private var cart`. If no ancestor supplied one, that read raises a runtime exception; declaring the property as `CartModel?` yields `nil` instead. Since `@State` creates its default value when SwiftUI creates the view, I keep the model's `init` cheap; building with Xcode 27 makes `@State` the `State()` macro, which creates it only the first time.
code
swift · 22 linesimport SwiftUI
@main
struct ShopApp: App {
@State private var cart = CartModel() // the owner
var body: some Scene {
WindowGroup {
CartBadgeLabel()
.environment(cart) // keyed by CartModel's type
}
}
}
struct CartBadgeLabel: View {
@Environment(CartModel.self) private var cart
var body: some View {
Label("Cart", systemImage: "cart")
.badge(cart.itemCount)
}
}go deeper
Recall that the view that creates a model owns it with @State, and children receive it as a plain property.
Explain how environment(_:) and @Environment(Type.self) share a model by type, and what the optional form changes.
Diagnose the reset from an inline-initialized model, the stale child holding @State on a passed-in model, and the missing-object crash in previews and reused views.
Set where feature models are owned (App, scene or feature root) so ownership is obvious in review, and how previews and sheets get their models.
## Why the cart resets A SwiftUI **view is a value**: a small struct that describes part of the screen. SwiftUI rebuilds these structs constantly; every time a parent's `body` runs, it creates new values for its children. Any ordinary stored property initialized inline is evaluated again as part of that. So a screen written like this has a bug: ```swift struct CartScreen: View { var cart = CartModel() // a new, empty cart on every rebuild var body: some View { CartList(cart: cart) } } ``` When the parent redraws (a tab badge changes, a theme flips), `CartScreen` is rebuilt, `CartModel()` runs again, and the view now holds a different, empty instance. Because the stored reference changed, SwiftUI updates the screen, and the user's items are gone. Nothing about `@Observable` is broken; the model simply had no owner that outlives the struct. ## Owning a model with @State **`@State`** asks SwiftUI to manage the storage. Apple's documentation describes it as telling SwiftUI to manage the instance: each time SwiftUI re-creates the view, it connects the property to the managed instance, giving one source of truth. The fixed version is `@State private var cart = CartModel()`. The model lives as long as the view keeps its identity, and it can equally be owned by a `Scene` or the `App` struct for app-wide state. When the default value runs depends on the toolchain: - Built with **Xcode 26 or earlier**, `@State` is a property wrapper, and Apple's documentation says it instantiates its default value whenever SwiftUI instantiates the view; extra instances are discarded, but their `init` still runs. - Built with **Xcode 27**, `@State` is the **`State()` macro**, which instantiates the default value the first time SwiftUI instantiates the view. Either way, keep the model's initializer free of side effects such as network calls, or create the model later in a `task` when it is expensive. ## Who declares what | Role of the view | Declaration | |---|---| | Creates and owns the model | `@State private var cart = CartModel()` | | Receives it, reads or writes in actions | `var cart: CartModel` | | Receives it, needs bindings for controls | `@Bindable var cart: CartModel` | | Reads it far from the owner | `@Environment(CartModel.self) private var cart` | A child must not declare `@State var cart: CartModel` for a model it is given. `@State` keeps the first value it stored, so if the parent later passes a different cart, the child keeps showing the old one. ## Sharing through the environment Passing `cart` through every initializer is fine for a shallow tree. When a tab badge, the cart list and the checkout button sit in different branches, the environment is simpler: 1. The owner stores the model with `@State`. 2. It calls **`environment(_:)`** with the model on an ancestor view. 3. Any descendant reads it with **`@Environment(CartModel.self)`**. The modifier keys the object by its **type**, and Apple's documentation notes that a view hierarchy's environment holds only one observable object of a given type. Passing `nil` clears an object of that type for the subtree. Reading from the environment does not change tracking: the reading view still depends only on the properties its `body` reads. ## Missing objects Reading `@Environment(CartModel.self)` as a non-optional assumes an ancestor supplied one. If none did, Apple's documentation says SwiftUI throws an exception, so the app crashes when that view is evaluated, which typically shows up first in a preview or in a view reused somewhere the model was never injected. Two defences: - declare `@Environment(CartModel.self) private var cart: CartModel?` where presence is not guaranteed, and handle `nil`; - attach `.environment(cart)` high enough to cover every place the reading view appears, and inject a sample model in previews. ## Mistakes reviewers catch - An inline-initialized model in a view that is not the root of its feature. - `@State` on a model that was passed in. - A non-optional environment read in a view that can also be shown outside the injecting hierarchy. - Heavy work in the model's `init`, which runs more often than expected under the property-wrapper `@State`. Custom environment keys, `@Entry` values and the object wrappers of the `ObservableObject` era are covered with environment values and with the older object wrappers.
- What happens if a view reads @Environment(CartModel.self) and no ancestor called environment(_:) with a CartModel?Apple's documentation says SwiftUI throws an exception, so the app crashes when that view is evaluated. If the model may legitimately be absent, declare the property as `CartModel?`; SwiftUI then returns `nil` instead of crashing.
- Can two different CartModel instances be in the environment for the same subtree?No. The environment of a view hierarchy holds one observable object per type, and the nearest `environment(_:)` call wins for its subtree. Two carts for one subtree need two distinct types, or a container model that holds both.
- Why should a model's init stay cheap even when it is held in @State?Built with Xcode 26 or earlier, `@State` instantiates its default value each time SwiftUI instantiates the view and discards the extras, so the `init` runs more than once. Xcode 27's `State()` macro creates it only the first time, but apps built with older toolchains still pay the cost.
- A class-typed property keeps its instance across view rebuilds by itself
- Marking the model @Observable stops SwiftUI from re-creating it
- A child should store a passed-in model in its own @State
- A missing environment object just yields a fresh default instance
- The environment can hold several CartModel instances for one subtree
Assumes iOS 17 or later for @Observable and environment(_:); building with Xcode 27 (Swift 6.4) turns @State into the State() macro, which creates a default model only the first time SwiftUI creates the view.