swiftui · note · identity
List Selection State in Navigation
Context
Navigation bugs often start as selection bugs. If the list row changes identity or the selection lives in the wrong place, the screen can look unstable even when the navigation code is correct.
The snippet
struct ItemList: View {
@State private var selectedID: UUID?
var body: some View {
List(items) { item in
Button(item.title) {
selectedID = item.id
}
}
}
}
Why this works
The list owns the selection state, so row recreation does not quietly reset it. That keeps navigation behavior predictable when the list updates.
Use it when:
- a row selection should survive list refreshes
- the visible choice matters outside the row
- you need a single source of truth for navigation state
Avoid it when:
- each row is truly independent
- the selection should be ephemeral
- you are storing navigation state in a child view by accident
Takeaway: Navigation feels stable when selection state lives above the rows that render it.