HeadlinesBriefing favicon HeadlinesBriefing.com

Swift Task Cancellation Explained

DEV Community •
×

Swift's Task cancellation isn't automatic; each task must manually validate cancellation. Calling `.cancel()` on a task reference doesn't immediately halt execution. The task's code must check its state using `Task.isCancelled` or `Task.checkCancellation()` to respond appropriately.

For example, wrapping a network call in a Task allows manual cancellation. If `URLSession` is used, it handles cancellation internally, throwing an `NSURLErrorDomain` code -999. Developers can also use `checkCancellation()` to throw a `CancellationError` or guard with `isCancelled` for custom logic.

In SwiftUI, tasks can be managed manually by storing a reference in `@State` and canceling in `.onDisappear`. Alternatively, the `.task` modifier automatically cancels the async operation when the view disappears, offering a cleaner, lifecycle-aware approach for UI-driven work.