skip to content

In SwiftUI, when do you create a binding with Binding(get:set:) or Binding.constant(_:) instead of passing a $ projection?

level: middleimportance: should knowfreq 40%

answer

  1. when no stored property matches
  2. a converted or derived value
  3. closures run on every read and write
  4. writes that go nowhere
  5. previews and placeholders

basics

~20 s

Binding(get:set:) adapts a source of truth whose stored shape differs from what a control needs, such as minutes over state kept in seconds. Binding.constant(_:) fills a binding parameter with a fixed value that ignores writes, typically in previews.

solid answer

~50 s

A `$` projection only exposes a stored property, or a field of it through a key path such as `$session.minutes`. When the control needs something the storage does not hold directly, `Binding(get:set:)` builds one from two closures: the getter derives the value, for example `durationSeconds / 60`, and the setter converts the write back into the source of truth. The source stays single; the custom binding is only an adapter. The closures run on every read and write, so they must stay cheap and side-effect free. `Binding.constant(_:)` returns a binding to an immutable value: reads return it and writes are ignored, which suits a `#Preview` or a disabled placeholder but makes a preview control look stuck. For an interactive preview, declare `@Previewable @State` inside `#Preview` instead (iOS 17 and later). Prefer the plain `$` projection whenever one exists.

code

swift · 26 lines
swift
import SwiftUI

struct FocusSettings: View {
    @State private var durationSeconds = 1_500

    var body: some View {
        DurationPicker(
            minutes: Binding(
                get: { durationSeconds / 60 },
                set: { durationSeconds = $0 * 60 }
            )
        )
    }
}

struct DurationPicker: View {
    @Binding var minutes: Int

    var body: some View {
        Stepper("\(minutes) min", value: $minutes, in: 5...90, step: 5)
    }
}

#Preview("Fixed duration") {
    DurationPicker(minutes: .constant(25))
}

go deeper

for a junior

Recall the two tools: Binding(get:set:) adapts a value into the shape a control needs, and .constant(_:) fills a binding that should never change, usually in a preview.

for a middle

Explain that a custom binding stores nothing, that its getter runs on every read, that constant drops writes, and why a key-path projection beats a custom binding when it exists.

for a senior

Review custom bindings for hidden side effects and second sources of truth, and move change handling to onChange on the real owner rather than inside the setter.

for a principal

Set expectations for shared components: accept bindings for edited values, keep conversions at the owner, and keep preview-only constants out of production code paths.

## Where projections run out Most bindings in SwiftUI come from the **`$` prefix**: `$minutes` on a `@State` property gives a `Binding` to its storage, and `$session.minutes` uses `Binding`'s dynamic member lookup to reach one field of a struct. This works as long as the control wants exactly what is stored. Two common situations break that assumption: - The stored value has a **different shape** from the one the control edits: the timer stores `durationSeconds`, but the picker edits whole minutes. - There is **no source of truth at all**, because the view is being previewed, prototyped or shown in a disabled, read-only state, yet the child's initializer still requires a `Binding`. `Binding` declares two creation APIs for these cases: `init(get:set:)` and the static `constant(_:)`. ## `Binding(get:set:)`: an adapter over one source of truth A custom binding is two closures. The **getter** computes the value the control sees; the **setter** receives the control's new value and writes the source of truth. Nothing is stored in the binding itself, so there is still one owner: 1. The timer screen owns `@State private var durationSeconds = 1_500`. 2. It creates `Binding(get: { durationSeconds / 60 }, set: { durationSeconds = $0 * 60 })`. 3. The picker reads minutes and writes minutes; the screen keeps seconds. Typical uses: - **Unit or type conversion**: seconds to minutes, an enum to a `Bool` for a `Toggle`, an index to a selection. - **Validation or clamping on write**: the setter can clamp a value before storing it. - **Bridging an optional**: presenting a value only when it exists. `Binding` also has a failable initializer, `Binding(_:)`, that turns a `Binding<Value?>` into a `Binding<Value>` or `nil`. Rules that keep custom bindings safe: - Keep both closures **cheap and free of side effects**. SwiftUI calls the getter whenever a view reads the binding, not once. - **Do not hide a second source of truth** inside the closures, such as reading and writing an unrelated global that SwiftUI does not track. - **Prefer a key path** (`$session.minutes`) over `Binding(get:set:)` whenever the field already exists; the projection is shorter and harder to get wrong. ## `Binding.constant(_:)`: a value that ignores writes `Binding.constant(_:)` returns a binding to an immutable value. Reads always return it; writes are dropped. That makes it the shortest way to satisfy a binding parameter when nothing should change: - in a `#Preview`, to render a child at a fixed value: `DurationPicker(minutes: .constant(25))`; - in a read-only or placeholder state of a screen. The catch is that interactive controls appear **frozen**: tapping the stepper in a preview does nothing, because the write goes nowhere. For a preview that should respond, declare the state inside the preview with `@Previewable @State var minutes = 25` (the `Previewable()` macro is available from iOS 17) and pass `$minutes`; previews themselves are covered in their own lesson. ## Choosing a binding source | You have | Use | Writes go to | |---|---|---| | A `@State` property of the right type | `$value` | The state's storage | | A field of a struct held in state | `$value.field` | That field, inside the stored struct | | Stored data in a different shape | `Binding(get:set:)` | Wherever your setter writes | | No source of truth (preview, placeholder) | `Binding.constant(_:)` | Nowhere, they are ignored | ## Common mistakes with custom bindings - **Shipping `.constant(_:)` outside previews** for a control the user can see: the control looks enabled but silently ignores input. Use `disabled(_:)` with a real binding instead. - **Building a custom binding to work around a missing key path** when the struct could simply expose the field; the key-path projection is shorter and keeps the code obvious. - **Ignoring a lossy conversion**: dividing seconds by 60 in the getter and writing `minutes * 60` back drops any leftover seconds the first time the user nudges the control, so decide whether that loss is acceptable or keep the remainder in the setter. ## Reacting to the derived value Because a custom binding writes the real source of truth, any side effect should watch that source, not the binding: `onChange(of: durationSeconds) { ... }` on the owner, using the two- or zero-parameter form available since iOS 17. Putting the side effect inside the setter couples it to one control and skips changes made from anywhere else.

  • Why does a Stepper in a preview built with .constant(25) not change when tapped?
    `Binding.constant(_:)` binds to an immutable value, so the stepper's writes are ignored and it keeps rendering 25. To make the preview interactive, declare `@Previewable @State var minutes = 25` at the root of the `#Preview` body and pass `$minutes`; `@Previewable` is available from iOS 17.
  • What goes wrong when a Binding(get:set:) getter does heavy work?
    SwiftUI calls the getter every time a view reads the binding, which can be on every evaluation of a `body` that uses it, so sorting, formatting or fetching there repeats constantly. Keep the getter a cheap derivation of stored data, and do expensive work once, when the source of truth changes.
  • How can a view show an editor only while an optional value in state is non-nil?
    Use `Binding`'s failable initializer: `if let duration = Binding($customDuration) { Stepper(value: duration, ...) }`. It returns a `Binding<Int>` when the optional holds a value and `nil` otherwise, so the editor writes straight into the optional's storage.

  • A binding made with .constant(_:) lets preview controls change their value.
  • Binding(get:set:) stores the value its getter returned the first time.
  • A derived binding needs its own @State to stay in sync with the source.
  • Binding(get:set:) is deprecated now that @Bindable exists.
  • The getter of a custom binding is a good place to load data.