How can I cancel Task in swift

Asked on 2025-10-11

1 search

To cancel a task in Swift, you can use the cancel() method on a Task instance. Swift's concurrency model allows you to manage tasks, which are the fundamental units of concurrent execution. When a task is no longer needed, you can cancel it to free up resources and prevent unnecessary work.

Here's a basic example of how you might cancel a task:

let task = Task {
    // Perform some work
    for i in 0..<10 {
        if Task.isCancelled {
            print("Task was cancelled")
            return
        }
        print("Working on \(i)")
        try await Task.sleep(nanoseconds: 1_000_000_000) // Simulate work
    }
}

// Cancel the task
task.cancel()

In this example, the task checks if it has been cancelled using Task.isCancelled and exits early if it has been. This is a common pattern to ensure that tasks can be cancelled gracefully.

For more detailed information on concurrency in Swift, you might find the session A Swift Tour: Explore Swift’s features and design helpful, as it covers concurrency concepts in Swift.