skip to content

In SwiftUI, how do you pass a TextField a binding to a property of an @Observable model, including one read from @Environment?

level: middleimportance: must knowfreq 68%

answer

  1. controls want a Binding
  2. a wrapper that only makes bindings
  3. dollar sign plus key path
  4. local variable inside body

basics

~10 s

Mark the model @Bindable and pass $model.property, as in $cart.couponCode. For a model read with @Environment, which offers no binding, declare @Bindable var cart = cart inside body and bind from that local.

solid answer

~40 s

Controls such as `TextField` and `Toggle` take a `Binding`, so I need one for `couponCode`. A child that receives the model declares `@Bindable var cart: CartModel` and passes `$cart.couponCode`; `@Bindable` makes bindings through key paths but does not own or create the object. The view that owns the model with `@State` can already write `$cart.couponCode`, because `Binding` supports dynamic member lookup. A model from `@Environment(CartModel.self)` has no `$` projection, so I declare `@Bindable var cart = cart` inside `body`, or write `Bindable(cart).couponCode` inline. Plain mutations in a button action need no wrapper at all, since the model is a class. `@Bindable` works only with `Observable` types; on an `ObservableObject` the compiler refuses and suggests `@ObservedObject`.

code

swift · 19 lines
swift
import SwiftUI

struct CouponField: View {
    @Environment(CartModel.self) private var cart

    var body: some View {
        @Bindable var cart = cart
        TextField("Coupon code", text: $cart.couponCode)
            .textInputAutocapitalization(.characters)
    }
}

struct GiftOptions: View {
    @Bindable var cart: CartModel     // passed in by the parent

    var body: some View {
        Toggle("Gift wrap", isOn: $cart.giftWrap)
    }
}

go deeper

for a junior

Recall that $model.property needs @Bindable on a passed-in model, and that a local @Bindable copy fixes the @Environment case.

for a middle

Explain why @State already projects bindings, why @Environment does not, and why @Bindable neither owns nor tracks.

for a senior

Pick the right declaration for each child (plain, @Bindable, never @State for a passed-in model) and spot constant bindings and hand-written Binding(get:set:) in review.

for a principal

Agree a house rule on how forms bind into shared models, so edit screens stay consistent and nobody reaches for wrappers from the ObservableObject era.

## Why a binding is needed at all An `@Observable` model is a class, so most code can change it directly: `cart.couponCode = ""` in a button action writes to the shared instance, and Observation notifies the views that read `couponCode`. Some controls, though, do not accept a value; they accept a **`Binding`**, a read-write handle they can push edits through. `TextField(_:text:)`, `Toggle(isOn:)`, `Picker(selection:)` and `Stepper(value:)` all work this way. The question is how to turn "the `couponCode` property of this cart" into a `Binding<String>`. ## The tool: @Bindable **`@Bindable`** is a SwiftUI property wrapper, available from iOS 17, whose job is to create bindings to the mutable properties of an `Observable` object. Its projected value supports dynamic member lookup, so `$cart.couponCode` produces a `Binding<String>` that reads and writes `cart.couponCode`. Three facts matter: - It **does not own** the object. It wraps a reference someone else created and keeps alive. - It **does not make tracking happen**; tracking comes from reads in `body`, with or without the wrapper. - It accepts **only `Observable` types**. Applied to an `ObservableObject`, the declaration is unavailable, and the compiler's message says "@Bindable only works with Observable types. For ObservableObject types, use @ObservedObject instead." ## Four places the model can come from | Where the view gets the model | How it gets a binding | |---|---| | It owns it: `@State private var cart = CartModel()` | `$cart.couponCode` works directly, through `Binding`'s dynamic member lookup | | A parent passes it in | declare `@Bindable var cart: CartModel`, then `$cart.couponCode` | | It reads it with `@Environment(CartModel.self)` | `@Bindable var cart = cart` as a local in `body`, then `$cart.couponCode` | | Only one binding is needed, once | `Bindable(cart).couponCode` inline | The `@State` row works because the projected value of `@State` is a `Binding<CartModel>`, and a binding to a class can produce bindings to its writable properties. A child that receives the model as a plain `var` has no projection at all, which is the gap `@Bindable` fills. ## The environment case `@Environment` has no projected value, so `$cart` does not exist on an environment property and the build fails. Apple's documentation for `Bindable` shows the pattern to use instead: 1. Read the model: `@Environment(CartModel.self) private var cart`. 2. At the top of `body`, shadow it: `@Bindable var cart = cart`. 3. Pass `$cart.couponCode` to the control. Property wrappers on local variables are legal Swift, and Apple's examples also use the same local form inside a `List` row closure to bind a field of each row's object. ## Choosing the declaration in a child - Reads only, or writes from action closures: a plain `var cart: CartModel` (or `let`). - Needs bindings for controls: `@Bindable var cart: CartModel`. - Never `@State var cart: CartModel` for a model passed in: `@State` would keep the first instance it was given and ignore later ones. - Never `@Binding var cart: CartModel` just to edit fields: that binds the *reference*, which is only useful when the child must replace or clear the whole object. ## What the binding does at runtime A binding made this way holds no copy of the text. Its getter reads `cart.couponCode` and its setter writes `cart.couponCode` on the shared instance, so: - each keystroke is a write to a tracked property, and every view whose `body` read `couponCode` is updated, the field included; - another screen showing the same cart sees the new code at once, because there is only one model; - there is nothing to "save back" when the form closes; to support Cancel, edit a draft copy and assign it on Save. ## Mistakes reviewers catch - Adding `@Bindable` to every model property "so it updates". Updates come from reads, not from the wrapper. - Trying `$cart.couponCode` on an `@Environment` property and reaching for `@EnvironmentObject` to make it compile, which needs an `ObservableObject`. - Using `Binding.constant(cart.couponCode)` in production code: a constant binding ignores writes, so typing does nothing. - Writing a `Binding(get:set:)` by hand for every field when `@Bindable` produces the same thing from a key path. The binding itself is ordinary SwiftUI `Binding` behaviour, covered with view-owned values and bindings; what is specific here is getting from an observable object to that binding.

  • Does a child that only toggles cart.giftWrap in a Button action need @Bindable?
    No. The model is a class, so `cart.giftWrap.toggle()` in the action writes to the shared instance and Observation notifies the views that read `giftWrap`. `@Bindable` is only needed when a control asks for a `Binding`, such as `Toggle(isOn:)`.
  • How do you bind a TextField to a field of each row object in a List of @Observable items?
    Inside the row closure, declare a local `@Bindable var item = item` and pass `$item.name` to the `TextField`. Apple's documentation shows exactly this pattern, and each row then binds to its own object.

  • @Bindable makes a view own and keep its model alive
  • Without @Bindable a view cannot observe an @Observable model
  • You can write $cart.couponCode directly on an @Environment property
  • @Bindable works on ObservableObject classes as well
  • Every mutation of an @Observable model requires a Binding