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.

Finish tasks in the background
Discover background execution advancements and understand how the system schedules runtime. We’ll discuss how to get the most out of background runtime to allow your app to deliver features in the background while maintaining a great foreground experience. We’ll also cover how APIs provide background runtime for your app, and how each API is tailored for different use cases — including new APIs in iOS and iPadOS 26 that let your app finish tasks as your app transitions from the foreground to the background.

A Swift Tour: Explore Swift’s features and design
Learn the essential features and design philosophy of the Swift programming language. We’ll explore how to model data, handle errors, use protocols, write concurrent code, and more while building up a Swift package that has a library, an HTTP server, and a command line client. Whether you’re just beginning your Swift journey or have been with us from the start, this talk will help you get the most out of the language.

Meet WebKit for SwiftUI
Discover how you can use WebKit to effortlessly integrate web content into your SwiftUI apps. Learn how to load and display web content, communicate with webpages, and more.