skip to content

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%

answer

  1. what ForEach keys each row by
  2. indices shift when messages arrive
  3. a fresh UUID on every decode
  4. id: \.self hashes the whole value

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.

solid answer

~40 s

`ForEach` needs each element to be uniquely identifiable: either the elements conform to `Identifiable`, or you pass `id:` with a key path to a unique property. Apple's documentation says each generated view implicitly gets an `id(_:)` with its element's identifier, so a row's `@State`, such as `isExpanded`, lives exactly as long as that ID. Rows lose the flag when the ID is unstable: `ForEach(messages.indices, id: \.self)` hands each position's state to a different message when one is inserted at the top; `id: \.self` on a `Hashable` message gives a new ID when a reaction or read receipt changes; `let id = UUID()` assigned while decoding produces new IDs on every refresh. Duplicate IDs leave SwiftUI unable to tell rows apart. The fix is a `Message: Identifiable` whose `id` is the server's message ID.

code

swift · 32 lines
swift
struct Message: Identifiable, Decodable {
    let id: String        // assigned by the server, stable across fetches
    let text: String
    var reactionCount: Int
}

struct MessageRow: View {
    let message: Message
    @State private var isExpanded = false

    var body: some View {
        Text(message.text)
            .lineLimit(isExpanded ? nil : 3)
            .onTapGesture { isExpanded.toggle() }
    }
}

struct ThreadView: View {
    let messages: [Message]

    var body: some View {
        ScrollView {
            LazyVStack(alignment: .leading) {
                // Identity follows message.id, so isExpanded survives refreshes,
                // inserts above the row and reaction updates.
                ForEach(messages) { message in
                    MessageRow(message: message)
                }
            }
        }
    }
}

go deeper

for a junior

Recall that ForEach needs Identifiable elements or an id: key path, and that each ID must be unique for the rows to behave.

for a middle

Explain that the element ID becomes the row's identity, then walk through why indices, id: .self on mutable values and per-fetch UUIDs each reset or misplace row state.

for a senior

Diagnose a thread where state jumps between rows or resets on refresh, trace it to the ID source, and fix the model so IDs come from the server and stay stable.

for a principal

Make stable identity a data-layer contract: models crossing into UI code carry server-assigned IDs, and pagination or merging code removes duplicates before views see them.

## How `ForEach` identifies rows `ForEach` builds one view per element of a `RandomAccessCollection`. Its declaration requires an `ID` type that is `Hashable`, and Apple's documentation states the rule plainly: either the collection's elements conform to `Identifiable`, or you pass an `id` parameter with a key path to a unique identifier, as in `init(_:id:content:)`. That ID is not only bookkeeping. Apple's `StateObject` documentation notes that a view inside a `ForEach` implicitly receives an `id(_:)` modifier using its data element's identifier. So **a row's identity is its element's ID**, and everything tied to identity follows it: - the row's `@State`, such as an `isExpanded` flag on a message; - whether `onAppear` runs again for that row; - whether a change animates as a move, an insertion or a deletion. Apple's list guide says unique identifiers let SwiftUI animate inserts, deletions and moves, and that the `ForEach` inside a list depends on this. A row keeps its expanded state exactly as long as its ID stays the same and stays unique. ## Four ways a chat thread loses row state 1. **Indices as IDs.** `ForEach(messages.indices, id: \.self)` identifies rows by position. When a new message is inserted at the top, every index now points at a different message, so each row's state stays with its position and appears on the wrong message. 2. **`id: \.self` on a mutable value.** If `Message` is `Hashable` and the code passes `id: \.self`, the ID is the whole value. A new reaction count, a read receipt or an edited text produces a different hash, so SwiftUI sees a deleted row and a new one, and the expanded flag resets. 3. **A new `UUID()` per fetch.** A model declared with `let id = UUID()` gets a fresh ID every time a refresh decodes it. Every refresh replaces every row, so all state resets and the list animates as if everything changed. 4. **Duplicate IDs.** The documentation requires unique IDs and does not define what happens otherwise. Two messages with one ID, often from overlapping pages of results, leave SwiftUI unable to tell the rows apart, so state and updates can land on the wrong row. ## Choosing the ID | ID choice | On insert above | On a field change | On refresh | |---|---|---|---| | Array index | State shifts to other messages | Kept | Kept by position, not message | | `id: \.self` on the whole value | Kept | Row reset | Kept if values are equal | | `UUID()` assigned at decode | Kept | Kept | Every row reset | | Server message ID via `Identifiable` | Kept | Kept | Kept | The last row is the answer: a message conforms to `Identifiable` with an `id` that the server assigns and that never changes for that message. Messages composed locally before the server confirms them need an ID created once, when the message is created, and kept for the message's whole life. ## Classes and `ObjectIdentifier` The standard library gives class types a default `Identifiable` implementation based on `ObjectIdentifier`, which its documentation says is only guaranteed unique for the lifetime of the object. If a refresh builds new message objects, each one has a new identity, which is the `UUID()` problem in another form. Give the class a stored `id` from the data instead. The protocol itself, by its own documentation, leaves the duration and scope of identity unspecified; it is up to the conforming type to provide one that is stable enough. For SwiftUI rows, stable means "the same message keeps the same ID across fetches, edits and moves". ## Related rules worth knowing - `id: \.self` is fine for values that never change and are unique, such as a fixed list of tab names. - The `Range<Int>` initializer of `ForEach` without an `id:` is intended for a constant range; for a count that changes, iterate identifiable data or pass an `id:`. - When a row should reset on purpose, for example when a message is replaced by a new version, a new ID is the right signal. - Editing actions, swipe actions and row selection belong to the lesson on list rows; this lesson is only about which identity each row gets.

  • Why is id: \.self risky even when every message in the thread is unique?
    Because the ID is the whole value. Any change to a hashed property, such as an edited text or a new reaction count, gives the row a different ID, so SwiftUI treats it as one row removed and another inserted: its `@State` resets and the change shows as a removal and insertion. `\.self` suits immutable, unique values like a fixed list of strings.
  • What happens if two messages handed to ForEach share an ID?
    Apple's documentation requires each element to be uniquely identifiable and does not define the result otherwise. In practice SwiftUI cannot tell the two rows apart, so state, updates and animations can attach to the wrong row. Remove duplicates by ID before the data reaches `ForEach`, for example when a newly loaded page overlaps messages already shown.
  • When is ForEach(0..<count) without an id: parameter acceptable?
    Only when the range is constant. The `Range<Int>` initializer without `id:` is declared for a constant range, so a count that changes at runtime should use identifiable data or an explicit `id:`, which lets SwiftUI know which rows were added or removed instead of reusing positions.

  • Array indices make good ForEach IDs because they are always unique
  • id: \.self is always safe for Hashable model structs
  • A UUID() assigned each time a fetch decodes a message is a stable ID
  • Duplicate IDs in ForEach are harmless; SwiftUI just shows both rows
  • ForEach keeps row state by array position whatever the IDs are