0
0
Swiftprogramming~5 mins

Cancellation handling in Swift

Choose your learning style9 modes available
Introduction

Cancellation handling lets your program stop a task that is no longer needed. This saves time and resources.

When a user closes a screen and you want to stop loading data.
When a network request is taking too long and you want to cancel it.
When a background task is no longer relevant because the user changed their mind.
When you want to stop a long-running operation to keep the app responsive.
Syntax
Swift
Task {
    do {
        try Task.checkCancellation()
        // Your work here
    } catch {
        // Handle cancellation here
    }
}

Task.checkCancellation() throws an error if the task was cancelled.

Use Task.isCancelled to check cancellation without throwing.

Examples
This example checks for cancellation in a loop and stops if cancelled.
Swift
Task {
    do {
        for i in 1...5 {
            try Task.checkCancellation()
            print("Working on step \(i)")
            try await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds
        }
        print("Task completed")
    } catch {
        print("Task was cancelled")
    }
}
This example uses Task.isCancelled to stop a loop when cancelled.
Swift
let task = Task {
    while !Task.isCancelled {
        print("Running...")
        try await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
    }
    print("Task stopped because it was cancelled")
}

// Later in code
// task.cancel() to stop the task
Sample Program

This program starts a task that prints steps with delays. After 1 second, it cancels the task. The task stops early and prints a cancellation message.

Swift
import Foundation

let task = Task {
    do {
        for i in 1...10 {
            try Task.checkCancellation()
            print("Step \(i)")
            try await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds
        }
        print("All steps done")
    } catch {
        print("Task was cancelled")
    }
}

// Cancel the task after 1 second
Task {
    try await Task.sleep(nanoseconds: 1_000_000_000)
    task.cancel()
}

// Keep the main thread alive to see output
RunLoop.main.run(until: Date().addingTimeInterval(2))
OutputSuccess
Important Notes

Always check for cancellation regularly in long tasks to stop quickly.

Cancellation throws a special error, so use try/catch to handle it.

Calling task.cancel() only requests cancellation; the task must check and stop itself.

Summary

Cancellation handling helps stop tasks that are no longer needed.

Use Task.checkCancellation() or Task.isCancelled to detect cancellation.

Handle cancellation with try/catch to keep your app responsive and efficient.