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?
answer
- IDs come from the model, never from UUID() or the index
- a branch means a different view
- id(_:) changes only for a deliberate reset
- AnyView rebuilds when the wrapped type changes
- a checklist, a lint rule and a reproducing preview
basics
~20 sIdentity 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.
solid answer
~50 sMost lost-state bugs are identity bugs, so I write the rules down. `ForEach` data is `Identifiable` with an ID taken from the model, such as a server or database key. A `UUID()` created in a computed `id` or inside `body` gives every element a new identity on each update, and an index or offset ties state to a position, so an insert at the top moves every row's state onto the wrong item. When only a modifier's value changes, keep one view with a conditional value, because `if`/`else` creates two views and switching between them resets the state. A changing `id(_:)` is allowed only as an intentional reset, with a comment. `AnyView` is avoided where `@ViewBuilder` or a generic works, because changing its wrapped type rebuilds the hierarchy. I enforce this with a review checklist, a lint rule for the mechanical cases, and a preview that reproduces each fixed bug.
code
swift · 30 linesimport SwiftUI
struct Message: Identifiable {
let id: Int // the server's key, stable across reloads
var text: String
}
struct ThreadView: View {
let messages: [Message]
var body: some View {
VStack(alignment: .leading, spacing: 8) {
// Identity comes from Message.id, so each row's state follows its message.
ForEach(messages) { message in
MessageRow(message: message)
}
}
}
}
struct MessageRow: View {
let message: Message
@State private var isExpanded = false
var body: some View {
Text(message.text)
.lineLimit(isExpanded ? nil : 2) // one view with a conditional value
.onTapGesture { isExpanded.toggle() }
}
}go deeper
Recall that ForEach needs Identifiable data or an id key path, and that state belongs to a view's identity.
Explain structural and explicit identity, and why if/else around the same view resets its state.
Diagnose lost state caused by generated or positional IDs, accidental id(_:) changes and AnyView type changes.
Turn identity into team rules: model IDs, conditional values over branches, deliberate resets only, enforced by review, lint and reproducing previews.
## Why identity is a team problem In SwiftUI, a view's state, such as its `@State` storage, belongs to the view's **identity**, not to the struct value that `body` returns. SwiftUI gives a view identity in two ways: **structurally**, from its type and position in the view hierarchy, and **explicitly**, from an ID such as the one `ForEach` reads from `Identifiable` data or the value passed to `id(_:)`. While the identity stays the same, state survives any number of body evaluations. When it changes, SwiftUI treats the result as a new view and its state starts over. That makes identity mistakes hard to catch in review. The code compiles, the screen renders, and the bug shows up only as a text field that empties, a row that collapses or an animation that fades instead of moving. In a list-heavy app the same few mistakes recur across features, which is why a lead turns them into explicit rules. ## The rules | Rule | The bug it prevents | |---|---| | `ForEach` data is `Identifiable` with an ID from the model | rows trading state after inserts, deletes or reorders | | No `UUID()` in a computed `id` or inside `body` | a new identity on every update, so state never survives | | No index or offset as the ID of changing data | state stays at a position while the items move | | A conditional value, not `if`/`else`, when only a modifier changes | the branch switch replaces the view and resets it | | `id(_:)` changes only as a deliberate reset | accidental resets of forms and scroll positions | | `@ViewBuilder` or generics instead of `AnyView` | the hierarchy rebuilt whenever the wrapped type changes | ### Stable IDs from the model Apple's documentation for `ForEach` requires either `Identifiable` elements or an `id` parameter. The team rule goes further: the ID should be the model's own key, such as a server ID or a database key. Two traps belong in the checklist by name: - **Generated IDs.** `var id: UUID { UUID() }`, or models created inside `body`, give each element a new ID on every evaluation, so SwiftUI sees every row as new each time. - **Positional IDs.** `id: \.offset` on `enumerated()` data, or `ForEach(items.indices, id: \.self)` for a list that changes, ties state to the slot rather than the item, so inserting at the top shifts every row's expanded state down by one. ### A branch means a different view An `if`/`else` in a view builder creates two separate positions in the hierarchy. If both sides hold the same component and differ only in one modifier, toggling the condition swaps one instance for the other and resets its state. One view with a conditional value, such as `.background(isHighlighted ? .yellow : .clear)`, keeps a single identity. The rule is not "never use `if`": a branch is right when the two sides really are different views, and the reviewer's question is which of the two the author meant. ### Deliberate resets with id(_:) Apple's documentation for `id(_:)` says that when the value changes, the view's identity, for example its state, is reset. That is a useful tool, such as clearing an editor form when the user selects a different record, but an accidental change is a bug. So an `id(_:)` whose value can change must carry a comment saying what it resets and why. ### AnyView Apple's documentation for `AnyView` says that whenever the type of the wrapped view changes, the old hierarchy is destroyed and a new one is created. A `@ViewBuilder` function or a generic parameter keeps the structure visible to SwiftUI, so `AnyView` is for the rare case where the type cannot be known at compile time. ## Enforcing the rules Rules in a wiki are forgotten. Three mechanisms make them stick: 1. **A review checklist** built from the table above, applied to every change that touches `ForEach`, `id(_:)` or conditional view code. 2. **A lint rule** in continuous integration for the mechanical cases, such as `UUID()` inside a computed `id` or `id: \.self` on a model type. 3. **A reproducing preview** for each fixed identity bug: insert at the top, toggle the flag, change the selection, and check that the state stays with the item it belongs to. ## Trade-offs Stable model IDs sometimes need a change upstream, such as asking the API for a key or adding one to local data, and a conditional value can make a modifier chain longer than two clear branches. Both costs are small next to bugs that appear only as state quietly moving to the wrong row.
- When is id: \.self acceptable in a SwiftUI ForEach?When the elements are unique and do not change while they are shown, such as a fixed list of distinct strings or enum cases; the values themselves are then the identity. It becomes a bug as soon as two elements can be equal, because SwiftUI then has no way to tell those rows apart.
- How would you find the identity bugs already in a large codebase?Search for the mechanical patterns first: `UUID()` in computed `id` properties, `id: \.offset` and `id: \.self` on model types, and `id(_:)` calls whose value changes. Then reproduce the reported symptoms in previews, such as an insert at the top of a list or a toggled highlight, and watch whether state follows the item or the position.
- Any Hashable value works as an ID, so a fresh UUID() per read is the safest choice.
- The array index is a fine ID because indexes are always unique.
- if/else and a ternary produce the same view, so the choice is only style.
- Adding .id(UUID()) is a good way to force a stale view to refresh.
- AnyView costs nothing, so wrap views in it to simplify return types.