tezvyn:

Swift Task

AI-drafted, machine-checkedSource: developer.apple.comintermediate
Swift Task

Task is the unit of concurrent work in Swift's structured concurrency model. Creating a Task starts an async job right away, and Swift tracks its priority, cancellation, and lifetime automatically instead of leaving you to manage threads by hand.

WHY IT EXISTS Before Swift concurrency, asynchronous code relied on completion handlers or GCD's DispatchQueue, which do not compose well: cancellation, error propagation, and priority had to be threaded through manually, and it was easy to leak work or call a completion handler twice. Task exists as the building block of structured concurrency, giving every unit of async work a defined lifetime, a parent, and automatic cancellation propagation.

THE MENTAL MODEL Think of a Task as a receipt for an order handed to a kitchen. You do not manage the cooks or the stove, that is the cooperative thread pool's job, you just hold the receipt, which lets you check if the order is ready, cancel it, or await the result. Structured tasks, created inside async let or a task group, are receipts your parent order refuses to close out until they are done.

HOW IT WORKS Task { } launches unstructured work immediately on Swift's cooperative thread pool, inheriting the current actor and priority unless told otherwise, and returns a handle you can await or cancel. Cancellation is cooperative: the task is only ever marked cancelled, its code must check Task.isCancelled or call Task.checkCancellation to actually stop. Structured alternatives, async let for a fixed number of children and a task group for a dynamic number, automatically cancel their children if the parent task is cancelled or throws, and the parent scope cannot exit until every child finishes, which is what makes them structured rather than fire and forget.

WHEN IT MATTERS It matters anywhere concurrent work needs a clear owner: a Task launched from a SwiftUI view's onAppear must be cancelled when the view disappears, or it keeps running and can crash by touching a deallocated view model. The footgun is treating cancellation as automatic: a plain Task { } does not stop just because the caller lost interest, the task body must actively check for cancellation, especially inside loops doing network or file work.

ONE CONCRETE EXAMPLE A SwiftUI screen starts a search request inside .task { await viewModel.search(query) }, a modifier that creates a Task tied to the view's lifetime and cancels it automatically when the view disappears. Inside search, a loop over paginated results calls try Task.checkCancellation() each iteration, so navigating away mid search stops the network calls instead of wasting bandwidth updating a view that no longer exists.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.