Keep SwiftUI Delete Confirmations Tied To The Right Revision
Someone taps Delete on “Trip notes.” While the confirmation is open, a refresh replaces that note with a newer version. They tap Delete again. Should the app remove the version they never saw?
For this example, the answer is no. We’ll capture the note’s identity, title and revision when deletion is requested, then check the current revision before removing anything. A confirmation is permission for a particular operation, not a blank check with a trash-can icon.
Our swipe-actions article already captures the selected item and suggests checking revisions when records can change. Here we’ll implement that check, exercise the failure paths, and use SwiftUI’s new item-based alert overload to keep the presentation small.
One optional value owns the alert
Apple’s WWDC26 presentation introduces item bindings for alerts and confirmation dialogs. With alert(_:item:actions:message:), a non-nil value presents the alert and supplies its content. Choosing an action dismisses it and clears the binding.
Sagar Unagar’s walkthrough is a useful introduction to that simpler state model. Here we’ll add the part a presentation API cannot decide: whether the operation is still valid when the person confirms it.
This is the title-and-actions builder overload, distinct from the older alert(item:content:) API that returns an Alert. There are two details worth separating from the SDK announcement:
- The
LocalizedStringKeyoverload used below is new in the Xcode 27 SDK, but its implementation supports iOS 15 and later. Apple’s current declaration and the installed SwiftUI interface agree; it forwards to the existing presentation API. Our complete example targets iOS 17, because it uses Observation. - Its generic value does not need to conform to
Identifiable. Our note has an ID because the deletion needs identity; theDeleteRequestitself doesn’t need a second presentation ID.
The code was compiled with Xcode 27.2 and Swift 6.4.2, targeting iOS 17. Native interaction checks ran on iOS 27.2 Simulator; that isn’t a claim of runtime testing on iOS 17. The explicit nonisolated annotations keep the value types independent of a project’s default MainActor setting.
Capture a value, check the current store
A request contains three immutable values:
| Value | Purpose |
|---|---|
| Note ID | Find the same record even if its position changes. |
| Revision | Detect an edit since the request was created. |
| Title | Keep the confirmation’s wording tied to what was requested. |
We use a fresh UUID as a local revision token whenever the title changes. Changing “Trip notes” to another title and back still produces a different revision. Comparing titles alone would miss that sequence.
Put this model in the sample app:
import Foundation
import Observation
nonisolated struct Note: Identifiable, Equatable {
let id: UUID
let revision: UUID
let title: String
init(id: UUID = UUID(), revision: UUID = UUID(), title: String) {
self.id = id
self.revision = revision
self.title = title
}
}
nonisolated struct DeleteRequest: Equatable {
let noteID: UUID
let revision: UUID
let title: String
}
nonisolated enum DeleteResult: Equatable {
case deleted, changed, missing
}
@MainActor @Observable
final class NoteStore {
private(set) var notes: [Note]
var pendingDeletion: DeleteRequest?
private(set) var status = ""
init(notes: [Note] = [Note(title: "Trip notes"),
Note(title: "Meeting notes")]) {
self.notes = notes
}
func requestDeletion(of id: UUID) {
guard pendingDeletion == nil,
let note = notes.first(where: { $0.id == id }) else { return }
pendingDeletion = DeleteRequest(
noteID: note.id, revision: note.revision, title: note.title
)
}
func rename(_ id: UUID, to title: String) {
guard let index = notes.firstIndex(where: { $0.id == id }),
notes[index].title != title else { return }
notes[index] = Note(id: id, title: title) // A fresh revision.
}
@discardableResult
func confirmDeletion(_ request: DeleteRequest) -> DeleteResult {
guard let index = notes.firstIndex(where: {
$0.id == request.noteID
}) else {
status = "That note is already gone. Nothing was deleted."
return .missing
}
guard notes[index].revision == request.revision else {
status = "That note changed. Review it before deleting."
return .changed
}
notes.remove(at: index)
status = "Deleted \(request.title)."
return .deleted
}
}
The store replaces a note with a new value when it renames it. A pending request retains its original fields. Capturing a reference to a mutable model object would not provide the same snapshot: another part of the app could edit the object behind the alert.
confirmDeletion looks up the current index by ID, checks its revision, and removes it synchronously on MainActor. There is no suspension between the check and mutation, so other work on that actor cannot slip an edit between them. It also preserves current values in every other row.
This store assumes unique, stable note IDs. Real records might contain text, attachments or permissions; every change relevant to deletion must advance the revision too. Don’t regenerate revisions merely because a refresh decoded an unchanged record. Use a stable revision from the authoritative store, or preserve the local token when its meaningful content is unchanged.
Put the alert on one stable owner
A Stack Overflow discussion about deleting the wrong row already has answers explaining the hazard of giving every row a presentation modifier controlled by the same Boolean. The API update doesn’t make that an unsolved problem. It lets us express the selected operation more directly.
This view owns one alert outside ForEach. Each row asks the store for a request; the alert’s Delete action uses the request passed into its closure, rather than reading a potentially changed selection or saved array index.
import SwiftUI
struct NotesView: View {
@Bindable var store: NoteStore
var body: some View {
List {
Section {
ForEach(store.notes) { note in
VStack(alignment: .leading, spacing: 8) {
Text(note.title)
.font(.headline)
Button("Delete…") {
store.requestDeletion(of: note.id)
}
.buttonStyle(.borderless)
.frame(minHeight: 44)
.accessibilityLabel("Delete \(note.title)")
}
}
}
if !store.status.isEmpty {
Section {
Text(store.status)
}
}
}
.navigationTitle("Notes")
.alert("Delete note?", item: $store.pendingDeletion) { request in
Button("Delete", role: .destructive) {
store.confirmDeletion(request)
}
Button("Cancel", role: .cancel) { }
} message: { request in
Text("Delete \"\(request.title)\"? This cannot be undone.")
}
}
}
Keep the store in the app’s @State, then show NotesView(store: store) inside a NavigationStack. Download the complete app and checks for a runnable setup.
The row button only requests confirmation. The destructive role belongs to the button that actually deletes. We use an alert here because there is one irreversible choice and no need to anchor a menu of actions to a row. If you use confirmationDialog instead, consider its popover anchor on iPad; putting it on the entire list doesn’t give it a row-specific anchor.
Apple also documents that presented alert data should remain unchanged; updates after presentation aren’t a way to rewrite its content. Leave this request alone while it is presented. If the underlying note changes, reject the operation and show the inline status after dismissal. The user can review the current note and request deletion again. Don’t silently replace the request with a fresh revision and treat the old confirmation as new consent.
Check both the operation and the presentation
The useful failure tests are small:
| Before the person confirms | Expected result |
|---|---|
| Requested note is unchanged | Delete that ID only, including when two notes share a title. |
| Requested note changed, even if its title changed back | Keep it and ask for another review. |
| Requested note was already removed | Report that it is gone; leave its former neighbor alone. |
| A different note changed | Delete the requested note and preserve the other edit. |
| Person cancels, then chooses another row | Keep both notes on cancellation; present the newly chosen row next time. |
The downloadable checks exercise those model rules and the actual alert. Native UI tests open the alert, inject a model edit or removal through a test-only notification, then confirm. They also check cancellation, reopening, the displayed title and accessibility-sized text. The exact article examples compile in Swift 6 mode with both ordinary and MainActor default isolation.
The checks use an in-memory store. They don’t establish database or server correctness. If deletion requires an await, an earlier local revision check is insufficient: the authoritative store must compare the expected revision and perform the deletion as one conditional operation. It must also enforce authorization and report failures. A UI snapshot cannot reserve a record across a network request.
For a local operation, the rule stays simple: capture what was requested, find what exists now, and only delete when the revision still matches.