Make SwiftUI Search Ignore Outdated Results
Type “sw,” then “swift.” The second request finishes first and displays useful results. A moment later, the older request times out and replaces the list with an error.
Many search implementations guard the success path and forget the failure path. Both paths can finish late. Both need to prove they still belong to the current request before changing the screen.
Cancellation helps, but identify the request too
SwiftUI’s task modifier with an ID cancels and restarts its task when the ID changes. That makes the query a natural lifecycle input:
// Attach to the search view, with query bound to .searchable:
.task(id: query) {
await model.search(query)
}
Cancellation remains cooperative. A callback adapter, cache lookup, or custom service can still return after its caller has been cancelled. Use cancellation to stop unnecessary work and request identity to decide whether a result is still relevant.
The following model works with an injected search service:
import Combine
import Foundation
struct SearchHit: Identifiable, Sendable, Equatable {
let id: Int
let title: String
}
@MainActor
final class SearchModel: ObservableObject {
enum State: Equatable {
case idle
case loading(String)
case results(String, [SearchHit])
case failed(String)
}
@Published private(set) var state: State = .idle
private var latestRequest = UUID()
private let load: @Sendable (String) async throws -> [SearchHit]
init(load: @escaping @Sendable (String) async throws -> [SearchHit]) {
self.load = load
}
func search(_ query: String) async {
let request = UUID()
latestRequest = request
guard !query.isEmpty else {
state = .idle
return
}
state = .loading(query)
do {
let hits = try await load(query)
guard request == latestRequest, !Task.isCancelled else { return }
state = .results(query, hits)
} catch {
guard request == latestRequest, !Task.isCancelled else { return }
if error is CancellationError {
state = .idle
return
}
state = .failed(query)
}
}
}
Each attempt gets a new token, even if two attempts use identical query text. Query equality alone would not distinguish an old retry from the current one. The token changes before the empty-query early return, so clearing the field invalidates an outstanding request too.
The main actor protects the UI state between suspension points. It does not force network requests to finish in the order they started. The checks after await handle that separate problem.
Keep the query attached to the displayed state
The enum stores the query that produced the results. A view can show those results only when that query matches the current field. If you intentionally retain the old list while loading, label that behavior clearly instead of presenting old matches as if they answered the new text.
The same association helps with error handling. A timeout for “sw” should not turn the current “swift” screen red. In the model, the request-token and cancellation checks run before either success or failure is committed.
Use stable result IDs supplied by your data source. An item’s title is not necessarily unique, and generating fresh random IDs on every render makes SwiftUI lose row identity. The example’s integer ID stands in for the catalog’s actual item identity.
Debouncing changes traffic, not correctness
You can add a short cancellable delay before calling load to avoid sending a request on every keystroke. Keep that delay inside the task owned by the query, and let a cancelled sleep exit normally through the cancellation path.
Do not use try? around the delay and then continue into the request regardless of cancellation. Also do not remove the identity check because the debounce appears to make overlap unlikely. A user can pause between keystrokes, and the network can still finish out of order.
For a service that shares work between callers, cancellation may have its own ownership rules. The generation-safe cache article covers that layer. Search presentation still needs to decide whether a delivered value belongs to the current UI request.
Test the order you are afraid of
Use a controllable service with one continuation per request. Wait until the old request has started, start the new one, complete the new one successfully, and then fail the old one. Assert that the successful new state survives.
Run the opposite result shape too: start a request, clear the query, and then complete the request successfully. The screen should stay idle. Neither test needs an arbitrary sleep or a real network timeout.
This is also where you can test repeated identical queries, leaving and returning to the screen, and a service that cooperates with cancellation. Our async testing post explains why explicit readiness signals make these tests easier to trust.
September 2026 review: the model compiles in Swift 6 mode with Xcode 27. Controlled-request checks passed for an obsolete failure arriving after newer success and for obsolete success arriving after the query is cleared. Those are model checks; the actual screen still needs UI and accessibility testing.
Search feels reliable when the screen tells a consistent story about the text currently in the field. Treat every completion, including an error, as a candidate result that must first prove it belongs there.