Pocket How
Swift and concurrency

Swift structured concurrency: async let, task groups and cancellation

iOS 17+, iPadOS 17+. Intermediate. By Cihat Salik, .

Short answer

Use async let for a fixed number of parallel calls and a task group when the count is dynamic. Both cancel and await their children when the scope exits. Prefer them over Task {}, use Task.detached almost never, check cancellation in long loops, and create AsyncStreams with makeStream so you can cancel the producer on termination.

Why structure matters

Task { } is the first concurrency tool most people learn, and it is the one that causes the most trouble later. An unstructured task has no parent. Nobody waits for it, nobody cancels it unless you keep the handle, and its errors vanish unless you look. Structured concurrency (SE-0304) gives child tasks a scope: they start inside a function, they finish before it returns, and cancelling the parent cancels them. The rest of this article is about using that structure on purpose.

All examples assume Swift 6 language mode and a small Sendable API client:

import Foundation

struct User: Sendable { let id: Int }
struct Post: Sendable { let id: Int }
struct Dashboard: Sendable { let user: User; let posts: [Post]; let unread: Int }

struct API: Sendable {
    func user() async throws -> User { User(id: 1) }
    func posts() async throws -> [Post] { [] }
    func unreadCount() async throws -> Int { 0 }
    func thumbnail(for id: Int) async throws -> Data { Data() }
    func upload(_ data: Data) async throws {}
}

async let for a fixed set of calls

When you know at compile time how many things you need, async let (SE-0317) is the simplest form:

func loadDashboard(api: API) async throws -> Dashboard {
    async let user = api.user()
    async let posts = api.posts()
    async let unread = api.unreadCount()
    return try await Dashboard(user: user, posts: posts, unread: unread)
}

All three requests start immediately as child tasks. The single try await waits for all of them. If one throws, the error propagates out of the function, and the others are cancelled and awaited before the function returns.

That last rule surprises people. An async let you never await is still awaited at the end of its scope, after being cancelled. You cannot use it to fire and forget. If you write async let _ = analytics.send() and return, the send is cancelled.

Task groups for a dynamic count

When the number of children depends on data, use a task group:

func thumbnails(for ids: [Int], api: API) async throws -> [Int: Data] {
    try await withThrowingTaskGroup(of: (Int, Data).self) { group in
        for id in ids {
            group.addTask {
                (id, try await api.thumbnail(for: id))
            }
        }
        var result: [Int: Data] = [:]
        for try await (id, data) in group {
            result[id] = data
        }
        return result
    }
}

Donny Wals’ TaskGroup explainer covers three details worth keeping in mind:

  • Results arrive in completion order, which is rarely the order you added them. Return the identifier with the value, as above, so you can put things back together.
  • A failing child does not cancel its siblings by itself. The error surfaces when you reach it in for try await. Once it is thrown out of the group’s closure, the group cancels the remaining children and waits for them.
  • The group waits for every child before returning, so a child task cannot outlive it. You do not need [weak self] in addTask.

If one failure should not abort the batch, catch inside the child and return a Result or an optional instead.

Limiting concurrency

Adding a thousand children at once starts a thousand downloads. To cap it, seed the group with a few tasks and add one more each time one finishes:

func thumbnailsLimited(for ids: [Int], api: API, limit: Int = 4) async throws -> [Int: Data] {
    try await withThrowingTaskGroup(of: (Int, Data).self) { group in
        var result: [Int: Data] = [:]
        var pending = ids[...]
        for _ in 0..<min(limit, pending.count) {
            let id = pending.removeFirst()
            group.addTask { (id, try await api.thumbnail(for: id)) }
        }
        while let (id, data) = try await group.next() {
            result[id] = data
            if let next = pending.popFirst() {
                group.addTask { (next, try await api.thumbnail(for: next)) }
            }
        }
        return result
    }
}

Discarding task groups

When children produce no result, such as uploads, writes or a server’s connection handlers, a regular group holds on to every finished child until you call next(). SE-0381 added discarding groups, available from iOS 17, which release each child as soon as it completes:

func uploadAll(_ files: [Data], api: API) async throws {
    try await withThrowingDiscardingTaskGroup { group in
        for file in files {
            group.addTask {
                try await api.upload(file)
            }
        }
    }
}

Because there is no next() to rethrow an error from, a throwing discarding group cancels itself and all siblings on the first child error and rethrows that error. That is the opposite of the regular group’s behavior, and usually what you want for a batch of side effects.

Cancellation is cooperative

Cancelling a task sets a flag. Nothing stops the code running. Each piece of work has to look at the flag and decide what to do. Most Apple async APIs, including URLSession and Task.sleep, check it for you and throw CancellationError. Your own loops need to check:

func checksum(of chunks: [Data]) async throws -> Int {
    var total = 0
    for chunk in chunks {
        try Task.checkCancellation()
        total &+= chunk.reduce(0) { $0 &+ Int($1) }
    }
    return total
}

Use Task.checkCancellation() when you want to stop by throwing, and Task.isCancelled when you want to return partial results.

When you wrap a callback API that has its own cancel method, connect the two with withTaskCancellationHandler:

final class LegacyDownload: @unchecked Sendable {
    func start(completion: @escaping @Sendable (Data?) -> Void) { completion(Data()) }
    func cancel() {}
}

func download(_ legacy: LegacyDownload) async -> Data? {
    await withTaskCancellationHandler {
        await withCheckedContinuation { continuation in
            legacy.start { continuation.resume(returning: $0) }
        }
    } onCancel: {
        legacy.cancel()
    }
}

The onCancel closure runs immediately on whatever thread cancels the task, possibly while the operation is still starting, so it must be safe to call at any time.

Work that must finish anyway

Sometimes cleanup has to complete even if the task was cancelled, such as flushing a file before closing a document. Swift 6.4 added withTaskCancellationShield (SE-0504), available from iOS 27, which hides the enclosing cancellation from the code inside it:

func flush() async {}

func closeDocument() async {
    if #available(iOS 27.0, macOS 27.0, *) {
        await withTaskCancellationShield {
            await flush()
        }
    } else {
        await flush()
    }
}

On earlier systems, an unstructured Task is the usual workaround, since it does not inherit cancellation.

Task, Task.detached and Task.immediate

Every unstructured task is a deliberate escape from structure. Use one at the boundary where synchronous code starts async work, such as a button action or onAppear, and keep the handle if the work can be cancelled.

@MainActor
final class SearchModel {
    var results: [Post] = []
    private var searchTask: Task<Void, Never>?
    let api = API()

    func queryChanged(_ text: String) {
        searchTask?.cancel()
        searchTask = Task {
            try? await Task.sleep(for: .milliseconds(300))
            guard !Task.isCancelled else { return }
            do {
                results = try await api.posts()
            } catch {
                results = []
            }
        }
    }
}

In SwiftUI, the .task modifier is usually better still: it is cancelled for you when the view disappears.

Task { } inherits the caller’s actor, priority and task-local values. Task.detached { } inherits none of them. In the Swift Forums thread on the two, David Smith suggests not using detached just to get off the current actor: put the work in a @concurrent function and call it from a normal Task, or call it directly if you are already in async code. Matt Massicotte’s problematic patterns list makes the same recommendation, because detached also silently drops priority and task locals.

Swift 6.2 added two related tools:

  • Task.immediate (SE-0472), available from iOS 26, starts running synchronously on the caller until its first suspension. Use it when the first part of the work must happen before the current event finishes, for example setting a loading state in the same frame. Task groups gained addImmediateTask for the same reason.
  • Task names (SE-0469): Task(name: "Prefetch") { } shows up in the debugger and Instruments. The initializer back-deploys; reading Task.name requires iOS 26.
@concurrent
func resize(_ data: Data) async -> Data { data }

@MainActor
func handleTap() {
    if #available(iOS 26.0, macOS 26.0, *) {
        Task.immediate {
            print("Runs synchronously until the first await")
        }
    }
    Task(name: "Prefetch") {
        _ = await resize(Data())
    }
}

Priority

Leave it alone in almost all app code. Child tasks inherit the parent’s priority, and the runtime escalates a task’s priority when a higher-priority task awaits it. Massicotte warns that explicit priorities can cause inversions, and suggests documenting why whenever you set one. Swift 6.2’s escalation APIs (SE-0462) exist for rare cases; Paul Hudson describes manual escalation as a last resort.

AsyncSequence and AsyncStream

An AsyncSequence delivers values over time, and you consume it with for await. The loop runs inside the current task, so cancelling the task ends the loop. AsyncStream is the standard way to adapt a callback or delegate API into one.

Create it with makeStream(of:bufferingPolicy:) (SE-0388), which back-deploys to iOS 13 and returns the stream and continuation as a pair:

func ticks(every interval: Duration) -> AsyncStream<Date> {
    let (stream, continuation) = AsyncStream.makeStream(
        of: Date.self,
        bufferingPolicy: .bufferingNewest(1)
    )
    let producer = Task {
        while !Task.isCancelled {
            continuation.yield(Date())
            try? await Task.sleep(for: interval)
        }
        continuation.finish()
    }
    continuation.onTermination = { _ in
        producer.cancel()
    }
    return stream
}

The producer here is an unstructured task, so it would not notice if the consumer stopped. The Swift Forums thread on this problem lands on two fixes. The common one is onTermination, which runs when the consuming task is cancelled while waiting, when the stream finishes, or when the stream is deallocated, and cancels the producer. Franz Busch recommends the fully structured version: run the producer and the consumer as two child tasks of one task group, so cancellation, priority and task locals all flow through. Use the structured version when you own both sides. Use onTermination when you return a stream to a caller you do not control.

Pick a buffering policy deliberately. The default is unbounded, which grows memory if the consumer is slow. For UI state such as location or progress, .bufferingNewest(1) keeps only the latest value.

Traps and edge cases

  • Ignored throwing tasks. Task { try await save() } drops the error. Swift 6.4 (SE-0520) warns about unused throwing tasks. Catch inside the task.
  • Sequential awaits that should be parallel. let a = try await x(); let b = try await y() runs one after the other. Use async let when they are independent.
  • Mutating captured state in children. Child task closures are sending, and they cannot mutate a shared local var. Return values from children and combine them in the group body.
  • Blocking inside a task. DispatchSemaphore.wait() or a long synchronous loop inside a task occupies a thread from the small shared pool that all tasks run on. Use async APIs, or check cancellation and keep chunks short.
  • async let in a loop. Each iteration’s binding is awaited at the end of that iteration. For parallel work across a loop, use a task group.

Which tool to use

Situation Tool
Two to five independent calls, known in advance async let
N calls with results withTaskGroup / withThrowingTaskGroup
N calls without results, stop on first failure withThrowingDiscardingTaskGroup (iOS 17)
Start async work from a button or callback Task { }, keep the handle if cancellable
Work tied to a view’s lifetime SwiftUI .task
Background CPU work A @concurrent function, awaited
Start synchronously before the first await Task.immediate (iOS 26)
Cleanup that must outlive cancellation withTaskCancellationShield (iOS 27)
Callback or delegate events over time AsyncStream.makeStream with onTermination
Escape the current actor, priority and task locals Task.detached, rarely

Sources and further reading

Read next