Why does a cancelled Swift Task still overwrite newer search results?
Question
Look at this SwiftUI search screen:
struct SearchView: View {
@State private var query = ""
@State private var items: [String] = []
@State private var errorMsg: String?
var body: some View {
List(items, id: \.self) { Text($0) }
.searchable(text: $query)
.onChange(of: query) { _, next in
Task {
do { items = try await load(next) }
catch { errorMsg = "Search failed" }
}
}
}
}You type "sw" (600 ms response), and 50 ms later type "swift" (120 ms response). "swift" renders first, then "sw" overwrites the list. Later, a teammate cancels old tasks, and every fast keystroke flashes "Search failed".
- Why did
"sw"overwrite"swift"? - Fix the view with
.task(id:)and cooperative cancellation without flashing false errors.
Show hints (3)
- "UNSTRUCTURED TASKS KEEP RUNNING"
Spawning
Task { }inside.onChangedoes not cancel the previous task whenquerychanges or when the view disappears. - "CANCELLATION IS COOPERATIVE"
SwiftUI's
.task(id: query)cancels the old task automatically. Your own code andURLSessionstill have to check or react to cancellation. - "FILTER CANCELLATION ERRORS"
Task.sleepandTask.checkCancellation()throwCancellationError.URLSessionthrowsURLError(.cancelled)(-999). Ignore both before settingerrorMsg.
Show checked explanation
Unstructured Task { } inside .onChange never cancels the "sw" request, so it finishes 430 ms after "swift" and overwrites items. Replace it with .task(id: query), which cancels the old task on every change and on view exit. Check Task.checkCancellation() in local loops, and ignore both CancellationError and URLError(.cancelled) so cancelled keystrokes do not show an error.
Out-of-order search races, .task(id:) cancellation, URLSession URLError(.cancelled), and cooperative checks were checked in a Python 3.12 task model against Swift 6 and iOS 18 documentation. Checked by an editor other than the author.
Walkthrough
Swift Concurrency separates structured work (bound to a scope or view lifetime) from unstructured Task { } handles that outlive their trigger unless you store and cancel them yourself.
| construct | cancels automatically? | cancellation signal |
|---|---|---|
Task { } in .onChange | no | manual handle .cancel() only |
.task(id: query) | yes, on id change or disappear | sets task cancelled flag |
async let / TaskGroup | yes, on scope exit or throw | propagates to all child tasks |
URLSession.data(from:) | aborts when task cancels | throws URLError(.cancelled) (-999) |
In the buggy view, typing "sw" at t = 0 ms starts a 600 ms request. Typing "swift" at t = 50 ms starts a 120 ms request that paints at t = 170 ms. Because nothing cancelled the first unstructured Task, "sw" finishes at t = 600 ms and replaces items.
Swift cancellation is cooperative. Calling .cancel() only marks the task as cancelled. Built-in suspension points respond immediately: Task.sleep throws CancellationError, and URLSession.shared.data(from:) aborts the socket request and throws URLError(.cancelled). Pure Swift work, such as filtering 50,000 cached items, keeps running unless you call try Task.checkCancellation() or inspect Task.isCancelled.
.task(id: query) {
do {
try await Task.sleep(for: .milliseconds(250))
let rows = try await load(query)
try Task.checkCancellation()
items = rows
errorMsg = nil
} catch is CancellationError {
return
} catch let e as URLError where e.code == .cancelled {
return
} catch {
errorMsg = "Search failed"
}
}The bare catch flashed "Search failed" because cancellation throws an error. Filtering out CancellationError and URLError(.cancelled) keeps normal typing silent while still reporting genuine network failures.
Common mistakes
- Assuming
task.cancel()forcibly stops running code. CPU loops ignore cancellation unless they checkTask.isCancelledor callTask.checkCancellation(). - Treating
CancellationErrororURLError(.cancelled)as a real failure and showing an error alert whenever the user types or switches tabs. - Launching unstructured
Task { }in.onChangeor UIKit handlers without storing the handle and cancelling it on new input ordeinit. - Assigning UI state right after
awaitwithout checkingTask.isCancelledwhen calling an API that swallows or misses cancellation.
Follow-up questions
- "Why does URLSession throw URLError(.cancelled) instead of CancellationError?" Foundation's
URLSessionreports cancelled network operations asURLErrorwith code.cancelled(-999), whereas Swift Concurrency APIs likeTask.sleepandTask.checkCancellation()throwCancellationError. Handle both before surfacing UI errors. - "When should you use Task.isCancelled instead of try Task.checkCancellation()?" Use
Task.isCancelledinside non-throwing functions or when you want to break out of a loop and return partial results cleanly. Usetry Task.checkCancellation()in throwing pipelines to unwind right away. - "How does async let behave if one of two parallel child fetches throws an error?"
async letcreates structured child tasks bound to the enclosing function. If the awaited fetch throws, Swift automatically cancels the siblingasync lettask and waits for it to exit before leaving the function.
What a strong answer covers
Distinguishes unstructured Task from .task(id:) and async let, explains cooperative checks (Task.checkCancellation() and Task.isCancelled), and catches both CancellationError and URLError(.cancelled) without flashing UI errors.
Open in interactive practice deck →