skip to content

Identity and Lifetime

Structural and explicit identity decide whether SwiftUI keeps a view's state or starts over. Interviewers use it to explain lost state, reset scroll positions and animations that never run.

on this pageshow

explore

questions

6

In SwiftUI, a view struct is recreated on every parent update, so why does its @State value survive, and what makes it start over?

level: juniorimportance: must knowfreq 66%

answer

  1. struct is a description, not the view
  2. storage managed outside the struct
  3. keyed to the view's identity
  4. removal or a new identity resets it

basics

~20 s

SwiftUI keeps @State storage outside the view struct and ties it to the view's identity, not the struct instance. A recreated struct reuses that storage; removing the view or changing its identity discards it, so the next view starts fresh.

solid answer

~50 s

A SwiftUI view struct is a cheap description that SwiftUI builds again whenever a parent's `body` runs. A `@State` value is not stored in that struct: SwiftUI manages the storage and associates it with the view's **identity**, meaning its type and position in the hierarchy, or an explicit `id(_:)` value. When a new struct arrives for the same identity, SwiftUI connects it to the existing storage, so a counter or a typed draft survives parent updates and new input values. Apple's documentation says the life cycle of state mirrors the view's life cycle: when an `if` removes the view, the view moves to the other branch, or its `id(_:)` or `ForEach` element ID changes, the storage is discarded and the next appearance starts from the declared initial value. That is why state is for transient UI values, not persistence.

code

swift · 25 lines
swift
struct TapCounter: View {
    let title: String
    @State private var taps = 0

    var body: some View {
        Button("\(title): \(taps)") { taps += 1 }
    }
}

struct CounterScreen: View {
    @State private var title = "Taps"
    @State private var showsCounter = true

    var body: some View {
        VStack {
            // Editing the title rebuilds TapCounter's struct; taps is kept.
            TextField("Title", text: $title)
            Toggle("Show counter", isOn: $showsCounter)
            // Hiding the counter discards its state; showing it again starts at 0.
            if showsCounter {
                TapCounter(title: title)
            }
        }
    }
}

go deeper

for a junior

Recall that a view struct is a throwaway description and that SwiftUI keeps @State outside it, tied to identity. Name one thing that resets it, such as an if removing the view.

for a middle

Explain identity as the key for state storage: structural position versus id(_:) and ForEach IDs. Show that new inputs keep state while removal or a new identity discards it.

for a senior

Use the lifetime rule to diagnose bugs: state seeded from an input that never updates, drafts lost when a branch flips, and state that should be hoisted to a parent that stays on screen.

for a principal

Frame the trade-off of where a value lives: view-owned state is cheap and local but dies with its identity, so anything users expect to keep must live in a model the team owns.

## The struct is not the view A SwiftUI **view** is a value of a type that conforms to `View`: usually a small `struct` with some input properties and a `body`. SwiftUI builds these structs again and again. Whenever a parent's `body` runs, every child written inside it is created as a new struct value with the current inputs. That is cheap by design, and it means the struct is a **description** of what should be on screen, not a long-lived object that sits on screen. If the struct were where a `@State` value lived, every parent update would wipe it. A counter would drop back to zero each time anything above it changed. That does not happen, and the reason is the subject of this lesson. ## Where `@State` lives When you mark a property with `@State`, you tell SwiftUI to **manage the storage**. Apple's documentation says exactly that: SwiftUI manages the property's storage, and when the value changes, it updates the parts of the hierarchy that depend on it. The storage is associated with the view's **identity**, which is how SwiftUI recognises "the same view" from one update to the next: - **Structural identity**: the view's type and its position in the hierarchy, including which branch of an `if` it sits in. - **Explicit identity**: a `Hashable` value attached with `id(_:)`, or the element ID a `ForEach` gives each of its views. When a new struct arrives for an identity SwiftUI already knows, SwiftUI connects it to the existing storage. The property reads the stored value, not the initial value written in the declaration. ## What ends a state's lifetime Apple's guide on managing user interface state puts it in one line: the life cycle of state variables mirrors the view life cycle. The view's life cycle is its identity's life cycle, so the storage is discarded when: - an `if` (or `switch`) stops producing the view, so it leaves the hierarchy; - the condition flips and the view moves to the other branch of an `if`/`else`, which is a different position; - the value passed to `id(_:)` changes; - a `ForEach` element's ID changes, or the element is removed from the data. The next time a view appears at that identity, it is a new view, and its `@State` starts from the declared initial value. ## What does not end it | Event | `@State` value | |---|---| | The parent's `body` runs again | Kept | | A `let` input of the view gets a new value | Kept | | The view's own `body` runs again | Kept | | The view is removed by an `if` | Discarded | | The view's `id(_:)` value changes | Discarded | The second row surprises people most. Apple's state guide describes a player view whose `episode` input changes: SwiftUI "recreates the `PlayerView` with a new input", and the player's own `isPlaying` state is untouched, because the identity did not change. ## The initial value expression The expression after `=` in `@State private var library = Library()`, where `Library` is an `@Observable` class, is evaluated when SwiftUI instantiates the view, and the build tool decides how often that is: 1. **Xcode 26 and earlier** use the `State` property wrapper. Its documentation says a `State` property always instantiates its default value when SwiftUI instantiates the view, so an expensive default is built again each time the view initializes, even though the stored value is what the view keeps showing. 2. **Xcode 27** uses the `State()` macro instead. Its documentation says a `State()` property instantiates its default value the first time SwiftUI instantiates the view, and Apple's SwiftUI updates page says this change only initializes and stores the property once when it is a class. Either way, the value you see is the stored one for that identity. The macro change belongs to the lesson on view-owned values; here it matters only because it narrows when a class-typed default is built. ## Practical consequences - **State is for transient UI values.** Apple's guidance is not to use state properties for persistent storage, because their lifetime is the view's. A relaunch builds new views with fresh state. - **Seeding state from an input works once per identity.** Apple's documentation warns that setting state's initial value in an initializer can interfere with SwiftUI's management of it. While the identity holds, SwiftUI keeps the stored value, so a new input does not reach it. - **Lift state up when it must outlive a branch.** If a value must survive a child being removed and shown again, store it in the parent that stays on screen and pass it down, or pass a binding. - **Change identity on purpose when you want a fresh start.** Giving a subtree a new `id(_:)` value is the documented way to make it start over.

  • A child view sets its @State from a parameter in its initializer. Why does it ignore later changes to that parameter?
    While the child keeps its identity, SwiftUI keeps the value already in storage, so the value computed from the new parameter is not used. Apple's documentation warns that setting state in an initializer can interfere with SwiftUI's management of it. Either let the parent own the value and pass it down or pass a binding, or tie the child's identity to the parameter with `id(_:)` so a new value means a new view with fresh state.
  • Why does Apple's documentation advise against using @State for persistent storage?
    Because the life cycle of a state variable mirrors the view's life cycle. The value exists only while that view identity is in the hierarchy: removing the view, changing its identity or relaunching the app builds a new view whose state starts from the initial value. Persistent data belongs in a model or storage layer that the view reads.

  • @State is stored inside the view struct, so a recreated struct must reset it
  • SwiftUI keeps one long-lived instance of each view struct and mutates it
  • A new value for a let input resets the child view's @State
  • A view hidden by an if keeps its @State until it is shown again
  • @State survives an app relaunch like a saved setting

Assumes Xcode 27 and the iOS 27 SDK, where @State builds as the State() macro, which creates and stores a class-typed default only once, when SwiftUI first instantiates the view.

open as a page

In a SwiftUI chat thread built with ForEach, why do message rows lose their expanded state, and how should each row be identified?

level: middleimportance: must knowfreq 64%

basics

~20 s

ForEach ties each row's identity, and so its @State, to the element's ID. Index IDs, id: .self on mutable values, fresh UUIDs per fetch and duplicate IDs all break that; conform messages to Identifiable with a stable, unique server ID.

open as a page

In SwiftUI, what is the difference between structural identity and explicit identity, and how does each decide whether a view keeps its state?

level: middleimportance: must knowfreq 72%

basics

~20 s

Structural identity is a view's type and position in the hierarchy, including which if branch it sits in; explicit identity is a Hashable value from id(_:) or a ForEach element's ID. Same identity keeps state; a new identity starts fresh.

open as a page

When would you deliberately change a SwiftUI view's id(_:) value to reset it, and what side effects come with that reset?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Change id(_:) when state derived once from an input must start over as that input changes, like a per-conversation composer. The reset is total: state, focus and owned models restart, onAppear and task run again, and inner changes don't animate.

open as a page

In SwiftUI, a text field empties whenever its parent toggles a highlight using if/else around the same child view; why, and how do you fix it?

level: seniorimportance: should knowfreq 56%

basics

~20 s

Each if/else branch is a separate structural identity, so flipping the condition replaces the child with a new one whose @State starts empty. Keep one view and put the condition inside the modifier's argument, or hoist the text into the parent.

open as a page

As the lead of a list-heavy SwiftUI app with recurring lost-state bugs, which identity rules would you put into code review, and how would you enforce them?

level: principalimportance: should knowfreq 25%

basics

~20 s

Identity decides how long state lives, so review it like data ownership: stable model IDs in ForEach, no generated or positional IDs, conditional values instead of if/else around one view, id(_:) only for deliberate resets, and no needless AnyView.

open as a page