skip to content

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%

answer

  1. two ways SwiftUI tells views apart
  2. type plus position in the hierarchy
  3. if/else branches are different positions
  4. id(_:) and ForEach element IDs

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.

solid answer

~40 s

SwiftUI has to decide whether a view in a new update is the *same* view as before. **Structural identity** answers that from the shape of `body`: a view's type and its position, so the first child of a `VStack` stays itself across updates, while the two branches of an `if`/`else` are two different views even when they build the same type. **Explicit identity** is a `Hashable` value you supply: `id(_:)` binds a view's identity to it, and `ForEach` gives each element's view the element's ID. When identity is unchanged, SwiftUI updates the view in place, so its `@State` survives and changes can animate. When identity changes, SwiftUI removes one view and inserts another: state resets, `onAppear` runs again, an unfinished `task` is cancelled, and changes inside it are not automatically animated in place.

code

swift · 38 lines
swift
struct BadgeView: View {
    let label: String
    @State private var isPinned = false

    var body: some View {
        Button(label) { isPinned.toggle() }
            .opacity(isPinned ? 1 : 0.6)
    }
}

struct NoteEditor: View {
    @State private var draft = ""

    var body: some View {
        TextField("Note", text: $draft)
    }
}

struct IdentityDemo: View {
    @State private var isPremium = false
    @State private var userID = 1

    var body: some View {
        VStack {
            // Structural: two branches, two BadgeViews; flipping resets isPinned.
            if isPremium {
                BadgeView(label: "Premium")
            } else {
                BadgeView(label: "Free")
            }
            // Explicit: a new userID gives NoteEditor a new identity and an empty draft.
            NoteEditor()
                .id(userID)
            Toggle("Premium", isOn: $isPremium)
            Button("Next user") { userID += 1 }
        }
    }
}

go deeper

for a junior

Recall the two kinds: position in the code versus a value you attach with id(_:) or a ForEach ID. Know that a new identity means fresh state.

for a middle

Explain how each kind changes, why if/else branches are separate identities, how ForEach applies element IDs, and what a reset brings: new state, onAppear again, a cancelled task.

for a senior

Read a body and predict which edits break identity, then fix lost state or missing animations by keeping one view with changing values or by choosing stable explicit IDs.

for a principal

Treat identity as a design constraint for shared views: decide which components may reset on input changes and document it, so screens built by different people behave predictably.

## Why SwiftUI needs identity Every time a `body` runs, SwiftUI gets a fresh tree of view values. To keep `@State`, to run `onAppear` only when something is really new, and to animate a change instead of swapping content, it has to answer one question for each view in the new tree: **is this the same view as before, or a different one?** The answer is the view's **identity**. SwiftUI uses two kinds. ## Structural identity **Structural identity** comes from the shape of the code in `body`: a view's **type** and its **position** in the hierarchy. Nothing has to be declared for it. - The second child of a `VStack` stays the same view across updates as long as the code keeps producing that type there. - The two branches of an `if`/`else` are **two different positions**, even when both branches create the same view type. Flipping the condition removes one view and inserts the other. - The same goes for the cases of a `switch`. Apple's documentation on transitions names `.id`, `if` and `switch` as identity-affecting changes that reset the state of the view they are applied to. - A view inside an `if` with no `else` exists only while the condition is true; when it turns false, that identity ends. ## Explicit identity **Explicit identity** is a `Hashable` value that you attach yourself. - The `id(_:)` modifier, declared as `func id<ID>(_ id: ID) -> some View where ID : Hashable` and available since iOS 13, binds a view's identity to the value. Apple's documentation says that when the value changes, the identity of the view (for example, its state) is reset. - `ForEach` uses explicit identity for each element. Its elements conform to `Identifiable`, or you pass an `id:` key path. Apple's documentation notes that a view inside a `ForEach` implicitly receives an `id(_:)` modifier that uses the identifier of its data element. ## The two side by side | Aspect | Structural identity | Explicit identity | |---|---|---| | Comes from | Type and position in `body` | A `Hashable` value: `id(_:)` or a `ForEach` element ID | | Changes when | A branch flips, or the code stops producing the view | The value changes | | Typical accident | `if`/`else` around the same child | `id: \.self` on a mutable value, or a new `UUID()` per update | | Deliberate use | Rare; usually you avoid flipping branches | Resetting a subtree when an input changes | ## What changes when identity changes When identity is unchanged, SwiftUI updates the existing view in place. When it changes, SwiftUI treats the update as removing one view and inserting another, and that has several effects: 1. `@State`, `@FocusState` and `@GestureState` values return to their initial values. Apple's `StateObject` documentation lists these explicitly, and an owned `StateObject` is created again. 2. `onDisappear` runs for the old view and `onAppear` for the new one. 3. A `task` that has not finished is cancelled, since its lifetime matches the view's; the new view starts its own. 4. Changes inside the view are not animated in place. The documentation says SwiftUI doesn't automatically animate changes inside a view whose identity changes at the same time; you see a removal and an insertion instead, which the lesson on insertion transitions covers. ## Identity is not equality Identity and equality answer different questions. Equality asks whether two values hold the same data; identity asks whether two values describe the same on-screen view over time. A row whose message text is edited keeps its identity, because its ID did not change, and SwiftUI updates it in place. Two rows holding identical text are still two identities when their IDs differ. Mixing the two up is behind the `id: \.self` bug, where an edit to a value changes its ID and resets its row. ## Reading a `body` for identity - Prefer **one view with changing values** over two branches that build the same view. A ternary inside a modifier argument keeps one identity. - Use `id(_:)` with a value that changes **only when you want a fresh view**, such as a record's ID. - Give `ForEach` IDs that are **stable and unique**, so each row keeps its own state as data moves. - When state must survive a branch flip, store it in a parent that stays on screen. These rules explain most reports of lost text, reset toggles, `onAppear` firing twice and animations that never run.

  • Does ForEach rely on structural or explicit identity for the views it creates?
    Explicit. Apple's documentation says a view inside a `ForEach` implicitly receives an `id(_:)` modifier with its data element's identifier. Identity therefore follows the element's ID rather than its index: a row keeps its state when its element moves, and loses it when the element's ID changes.
  • Is attaching id(_:) with a value that never changes harmful?
    No. Identity resets only when the value changes, so a constant value leaves the view's state alone. The danger is the opposite case: a value that changes on every update, such as `UUID()` created inside `body`, gives the view a new identity each time, so its state resets and its subtree is rebuilt.

Structural identity is a seat number in a theatre: row C, seat 4 is the same seat however the person in it changes, but a different seat is a different place. Explicit identity is the name on the ticket: print a new name and it is a different guest, wherever they sit.

  • Two if/else branches that build the same view type share one identity
  • Structural identity is the memory address of the view struct
  • id(_:) only has an effect inside List or ForEach
  • Explicit identity means SwiftUI compares all of the view's properties for equality
  • A changed identity is just a redraw that keeps the view's state