download

Why does a cancelled Swift Task still overwrite newer search results?

Mobile~8 minReviewed 2 Dec 2026Free · No sign-in

Question

Look at this SwiftUI search screen:

"SWIFT"
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".

  1. Why did "sw" overwrite "swift"?
  2. Fix the view with .task(id:) and cooperative cancellation without flashing false errors.
Show hints (3)
  1. "UNSTRUCTURED TASKS KEEP RUNNING"

    Spawning Task { } inside .onChange does not cancel the previous task when query changes or when the view disappears.

  2. "CANCELLATION IS COOPERATIVE"

    SwiftUI's .task(id: query) cancels the old task automatically. Your own code and URLSession still have to check or react to cancellation.

  3. "FILTER CANCELLATION ERRORS"

    Task.sleep and Task.checkCancellation() throw CancellationError. URLSession throws URLError(.cancelled) (-999). Ignore both before setting errorMsg.

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.

constructcancels automatically?cancellation signal
Task { } in .onChangenomanual handle .cancel() only
.task(id: query)yes, on id change or disappearsets task cancelled flag
async let / TaskGroupyes, on scope exit or throwpropagates to all child tasks
URLSession.data(from:)aborts when task cancelsthrows 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.

"SWIFT"
.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 check Task.isCancelled or call Task.checkCancellation().
  • Treating CancellationError or URLError(.cancelled) as a real failure and showing an error alert whenever the user types or switches tabs.
  • Launching unstructured Task { } in .onChange or UIKit handlers without storing the handle and cancelling it on new input or deinit.
  • Assigning UI state right after await without checking Task.isCancelled when calling an API that swallows or misses cancellation.

Follow-up questions

  • "Why does URLSession throw URLError(.cancelled) instead of CancellationError?" Foundation's URLSession reports cancelled network operations as URLError with code .cancelled (-999), whereas Swift Concurrency APIs like Task.sleep and Task.checkCancellation() throw CancellationError. Handle both before surfacing UI errors.
  • "When should you use Task.isCancelled instead of try Task.checkCancellation()?" Use Task.isCancelled inside non-throwing functions or when you want to break out of a loop and return partial results cleanly. Use try 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 let creates structured child tasks bound to the enclosing function. If the awaited fetch throws, Swift automatically cancels the sibling async let task 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 →

Original OfferVibe question. The Swift Programming Language: Concurrency · Swift Task · CancellationError · Foundation URLSession.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.