skip to content

In SwiftUI, a focus timer's DurationPicker seeds its @State from a preset parameter in init; why does it keep showing the first preset after the parent passes a new one?

level: seniorimportance: should knowfreq 60%

answer

  1. who owns the duration now
  2. storage outlives the struct
  3. initial value used once per identity
  4. private state, not an init parameter
  5. binding, onChange or a new id

basics

~20 s

SwiftUI keeps @State storage for as long as the view keeps its identity and applies an initial value only when it first creates that storage. Later inits that pass a new preset are ignored, so the picker keeps editing its own stale copy.

solid answer

~50 s

`@State` storage belongs to SwiftUI, not to the struct. When the parent's `body` runs again, SwiftUI builds a new `DurationPicker` and runs its `init`, but the picker still has the same identity, so SwiftUI keeps the duration it already stores; the new preset is never applied. That is why Apple's documentation says to declare state `private` and give its value at the declaration rather than set it in an initializer. The fix depends on who should own the value. Usually the parent does, so the picker takes `@Binding var minutes: Int` and there is nothing to resync. If the picker really owns a draft, resync it with `.onChange(of: preset) { _, newValue in minutes = newValue }`. If every piece of the picker's state should restart, give it a new identity with `.id(preset)`, accepting that this resets all of its state.

code

swift · 23 lines
swift
import SwiftUI

// Bug: the preset seeds private storage once; later presets are ignored.
struct DurationPicker: View {
    @State private var minutes: Int

    init(preset: Int) {
        self.minutes = preset
    }

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

// Fix: the parent owns the duration and the picker edits it.
struct BoundDurationPicker: View {
    @Binding var minutes: Int

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

go deeper

for a junior

Recall that @State is created once per view and a value passed into init later does not replace it; a child that edits a parent's value takes a binding.

for a middle

Explain storage tied to identity, the initial value used only on first creation, and why the documentation insists on private state with its value at the declaration.

for a senior

Diagnose it from logs, then pick the fix by ownership: binding when the parent owns it, onChange for a cancellable draft, and id only when the whole subtree should restart.

for a principal

Turn the bug into a review rule for the team: no @State seeded from parameters without a stated owner, and document which components own drafts versus edit bindings.

## The symptom A focus-timer screen offers preset chips (15, 25, 50 minutes) and shows a `DurationPicker` child for fine-tuning. The picker was written to own its value, seeded from the parent: - it declares `@State private var minutes: Int`; - its `init(preset: Int)` sets `self.minutes = preset`. The first preset appears correctly. After that, tapping another chip changes the parent's `preset`, the parent's `body` runs, a new `DurationPicker(preset:)` is created, and the picker still shows the old number. Logging in `init` proves it runs with the new preset, which makes the bug look impossible. ## Why the new value is ignored The explanation is the ownership model of `@State`: 1. **The struct is not the storage.** A `View` struct is a short-lived description. `@State` keeps the value in storage that SwiftUI manages for the view. 2. **Storage is tied to identity.** As long as the picker stays at the same place in the hierarchy with the same explicit id, SwiftUI treats it as the same view and keeps its stored state. Apple's documentation notes that changing a view's identity resets the state it holds, which implies the converse: an unchanged identity keeps it. 3. **The initial value is an initial value.** What you assign in `init`, or write at the declaration, seeds the storage the first time SwiftUI creates it. On later initializations SwiftUI supplies the stored value before `body` runs, and the new seed has no effect. Apple's `State` documentation states the rule from the other side: declare state `private` so it is not set from an initializer, which can conflict with the storage management SwiftUI provides. Under Xcode 27 `@State` is implemented by the `State()` macro, and its documentation keeps the same advice. ## Three fixes, by who should own the value | Fix | Owner of the duration | Cost | |---|---|---| | Child takes `@Binding var minutes: Int` | The parent | None; usually the right answer | | Child keeps a draft and resyncs with `onChange(of:initial:_:)` | The child, refreshed by the parent | Two copies to reason about; the draft is overwritten on each new preset | | Parent applies `.id(preset)` to the child | The child, recreated per preset | Resets **all** the child's state, and SwiftUI does not animate changes inside a view whose identity changes at the same time | - **Lift the state.** If the parent's preset and the picker's value are the same thing, there should be one source of truth: the parent's `@State`. The picker becomes `@Binding var minutes: Int` and edits it directly, so a reset or a new preset is visible immediately. - **Resync a draft.** Some editors genuinely own a draft that the user may cancel. Then keep `@State` in the child and add `.onChange(of: preset) { _, newValue in minutes = newValue }`, the two-parameter form available since iOS 17. - **Change identity.** `.id(preset)` makes SwiftUI treat each preset as a new view, so the picker's state is created fresh with the new seed. Use it when the whole subtree should restart, not to patch one value. ## Confirming the diagnosis Before changing code, prove that stored state is the cause: 1. Log the incoming `preset` in the child's `init`; the new value arrives, so the parent is fine. 2. Log `minutes` in the child's `body`; it still shows the old number, so the child is reading stored state. 3. Temporarily add `.id(preset)` on the child; if the picker now follows each preset, the stale value was state kept across an unchanged identity. 4. Remove the experiment and apply the fix that matches ownership. ## How to recognise it in review - A `@State` property assigned from an initializer parameter, through `self.minutes = ...` or the underscored storage. - A non-`private` `@State`, which lets the memberwise initializer accept a value from the caller. - A child whose name suggests it edits the parent's value ("picker", "editor") yet declares `@State` instead of `@Binding`. Ask the question that settles each case: **who owns this value?** If the answer is the parent, the child should not have state for it. ## Related behaviour, covered elsewhere How structural and explicit identity are decided, and why an `if`/`else` branch can reset state, belongs to the lesson on view identity and lifetime. The same seeding trap with the older `@StateObject` wrapper, where only the first autoclosure call creates the object, belongs to the lesson on object ownership wrappers.

  • When is applying .id(preset) to the picker the right fix rather than a binding?
    When the child legitimately owns a whole set of state that should restart from scratch for each input, such as a multi-step editor seeded from a template. Changing the id gives SwiftUI a new view, so every `@State` in that subtree is recreated. It also resets focus state, and SwiftUI does not animate changes inside a view whose identity changes at the same time.
  • Does building with Xcode 27, where @State becomes the State() macro, fix this bug?
    No. The macro changes when a class-typed default value is created, not who owns the storage. Its documentation still says to declare state `private` rather than set it in an initializer, and a view with an unchanged identity still keeps the value SwiftUI stores for it.
  • When is seeding @State from an initializer parameter acceptable?
    When the parameter really is a starting value that will not change for that view's identity, such as an editor shown in a sheet that is created fresh for each presentation and edits a draft the user can cancel. Name the parameter as an initial value, keep the state `private`, and write the commit back through a binding or a closure when the user saves.

  • Re-running the child's init applies the new initial value to its @State.
  • Making the @State property non-private fixes the stale value.
  • Adding .id(preset) is free, since it only refreshes the one value.
  • Xcode 27's State() macro makes seeding @State from init work.
  • An onAppear in the child will pick up each new preset automatically.