A SwiftUI contacts list sets selectedContact and then a Bool to open an edit sheet, but the sheet sometimes shows no contact or the previous one; why, and how do you fix it?
answer
- two states for one fact
- the closure reads separate state
- make the data the trigger
- sheet(item:) with an Identifiable value
basics
~20 sThe Bool and selectedContact are two separate states describing one fact, so the sheet's closure can read a value from before the update. Present with sheet(item: $selectedContact) instead: the sheet appears when the contact is non-nil and receives that contact.
solid answer
~50 sWith `sheet(isPresented:)` the presentation is keyed only to the Bool, and the content closure reads `selectedContact` on its own. Nothing ties the two writes together, so the closure can run against an earlier value: the commonly reported symptom is an empty editor on the first tap and the previously tapped contact afterwards. The fix is to make the data the trigger: `sheet(item: $selectedContact)` presents when the optional is non-nil, passes the unwrapped contact into the closure, and SwiftUI sets it back to `nil` on dismissal. The item must be `Identifiable`, and the documentation says that if the item changes while presented, the system dismisses the sheet and presents a new one. So the editor's `@State` draft starts from the right contact each time, and the `id` must be stable, or re-reading the selected contact after a refresh will re-present the sheet.
code
swift · 23 linesstruct Contact: Identifiable {
let id: String // the server's identifier, stable across refreshes
var name: String
}
struct ContactEditor: View {
let contact: Contact
var body: some View { Text("Editing \(contact.name)") }
}
struct ContactsList: View {
let contacts: [Contact]
@State private var editing: Contact?
var body: some View {
List(contacts) { contact in
Button(contact.name) { editing = contact }
}
.sheet(item: $editing) { contact in
ContactEditor(contact: contact)
}
}
}go deeper
Recall that sheet(item:) takes an optional Identifiable value, shows the sheet when it is non-nil, and hands that value to the content closure.
Explain why a Bool plus a separate selection is two sources of truth, and what sheet(item:) does when the item becomes nil or changes.
Diagnose the stale sheet from the symptom, fix it with an item-driven presentation, and check identifier stability so refreshes do not dismiss an editor mid-edit.
Turn the fix into a review rule: presentation state that needs data must be the data itself, and model identifiers must be stable before views key presentations on them.
## The symptom A contacts list keeps `@State private var selectedContact: Contact?` and `@State private var isEditing = false`. Tapping a row runs `selectedContact = contact; isEditing = true`, and `.sheet(isPresented: $isEditing) { ContactEditor(contact: selectedContact) }` opens the editor. In testing it mostly works; in the field people report an **empty editor on the first tap**, or **the contact they tapped before**. The bug is intermittent, which is why it reaches production. ## Why two pieces of state go wrong The design has a flaw independent of any timing detail: 1. **Two sources of truth describe one fact.** "The editor is open for contact X" is stored as a Bool *and* an optional, and nothing makes them change together. 2. **The presentation is keyed only to the Bool.** `sheet(isPresented:)` knows nothing about `selectedContact`; it only knows when to show its content. 3. **The content closure reads the selection on its own.** It is an escaping closure that SwiftUI calls when it builds the sheet. SwiftUI's documentation does not promise that the closure observes your two writes as one update, and a frequently reported trigger is a `body` that never reads `selectedContact` outside the closure, so the closure in use was produced before the selection changed. 4. **The editor caches what it received.** If `ContactEditor` copies its input into `@State`, that state is created once for the editor's lifetime. While the sheet stays presented, a new selection does not reset it, which is how "the previous contact" survives. Whatever the precise trigger in a given build, the cure is the same: stop describing one fact with two values. ## sheet(item:) makes the data the presentation `sheet(item:onDismiss:content:)` takes a `Binding<Item?>` where `Item: Identifiable`, and Apple's documentation describes its contract: - When `item` is non-nil, the system passes the item into the `content` closure, and you build the sheet from that value. - If `item` changes, the system **dismisses the sheet and replaces it** with a new one using the same process. - On dismissal, the binding returns to `nil`, so "no sheet" and "no selection" are one state. ```swift @State private var editing: Contact? List(contacts) { contact in Button(contact.name) { editing = contact } } .sheet(item: $editing) { contact in ContactEditor(contact: contact) } ``` The closure's parameter is the contact that triggered the presentation, so there is nothing stale for it to read. ## Identity: when the sheet is replaced Because the sheet is tied to the item's identity, two follow-on behaviours matter in production: - **A fresh editor per contact.** A new item means a new presentation, so an editor that initialises `@State` from its input starts from the right contact every time. (How `@State` lifetime follows view identity is covered with SwiftUI identity and lifetime.) - **The id must be stable.** If `Contact` declares `let id = UUID()` and the list is rebuilt from a server response, each refresh produces new ids for the same people. If the screen also keeps `editing` in sync with the refreshed data (re-reading the selected contact from the new array), each refresh writes a value with a new identity, the item has changed, and the sheet is dismissed and presented again, losing any unsaved edits. Use the server's identifier as `id`. ## Diagnosing it in a real codebase - Search for `.sheet(isPresented:` whose content closure reads an optional with `!`, `??` or `if let`. That optional is the real trigger and should drive the sheet. - Check whether the editor copies its input into `@State`; if so, confirm each presentation creates a new editor. - Log the `id` of the item each time the sheet appears. Unexpected re-presentations with the same person but a new `id` point to unstable identifiers. - Reproduce with a fast double tap on two rows; the stale case shows up far more often than with slow taps. ## The same rule elsewhere | Presentation | Bool form | Item form | |---|---|---| | Sheet | `sheet(isPresented:…)` | `sheet(item:…)` | | Full-screen cover | `fullScreenCover(isPresented:…)` | `fullScreenCover(item:…)` | | Popover | `popover(isPresented:…)` | `popover(item:…)` | | Alert, dialog | `presenting:` with a Bool | `alert(_:item:…)`, `confirmationDialog(_:item:…)` in the iOS 27 SDK | The rule of thumb a senior engineer states: **if the presented content needs data, let the data drive the presentation.** Keep `isPresented:` for content that needs nothing beyond "open" and "closed".
- What happens with sheet(item:) if the bound item changes while the sheet is up?Apple's documentation says the system dismisses the sheet and replaces it with a new one built from the new item. That is usually what you want when a different contact is chosen, but it also means an unstable `id` on the same contact causes a dismiss and re-present, losing in-progress edits.
- When is sheet(isPresented:) still the right choice?When the sheet's content needs no data beyond being open, such as a settings form or an add-contact form that starts empty. Then one Bool is the whole fact and there is no second state to drift. Once the content depends on which record was chosen, switch to the item form.
- Why might an item-driven editor still show out-of-date values?Usually because of what the editor does with its input. If it copies the contact into `@State` when it is created, that copy is a snapshot: later changes to the source record do not flow into it while the same sheet stays up. If it instead reads a long-lived shared model, it shows whatever that model holds. Decide explicitly whether the editor edits a snapshot or the shared model.
Telling a courier to deliver whatever is on your desk when he arrives, versus handing him the sealed envelope: with the Bool, the sheet fetches whatever the selection holds when it gets there; with sheet(item:), it is handed the contact itself.
- Setting the selection before the Bool guarantees the sheet sees the new value.
- sheet(item:) updates the open sheet in place when the item changes.
- Any Hashable type works as the item for sheet(item:).
- Regenerating UUID ids on each fetch is harmless for an item-driven sheet.
- The fix is to add a short delay before setting the Bool to true.