← Back to Swift Course | Chapter 13: Concurrency | Lesson 5 of 6

Structured Concurrency

Structured concurrency means related pieces of work are grouped together neatly, so they all finish (or all get cancelled) as a tidy unit, instead of scattering off on their own.

Concurrent Work with async let

async let starts an asynchronous operation immediately and lets it run concurrently with the rest of the function, until its value is awaited.

Example: Concurrent Work with async let

markup
func fetchFirstName() async -> String {
    return "Ada"
}
func fetchLastName() async -> String {
    return "Lovelace"
}

async let first = fetchFirstName()
async let last = fetchLastName()
let fullName = await "\(first) \(last)"
print(fullName)

Grouping Tasks with withTaskGroup

withTaskGroup lets you add a dynamic number of child tasks and collect their results together as a structured, awaitable unit.

Example: Grouping Tasks with withTaskGroup

markup
func square(_ n: Int) async -> Int {
    return n * n
}

let total = await withTaskGroup(of: Int.self) { group in
    for number in 1...4 {
        group.addTask {
            await square(number)
        }
    }
    var sum = 0
    for await result in group {
        sum += result
    }
    return sum
}
print("Sum of squares: \(total)")
Common Mistakes
  1. Launching several independent Task { } blocks for related work instead of grouping them with async let or a task group, making cancellation and error propagation harder to manage.
  2. Forgetting async let bindings run concurrently as soon as declared, but each one must still be awaited to retrieve its result.
  3. Using a task group but forgetting to await all its child tasks before the group's with...TaskGroup block ends.
Chapter Summary
  • async let starts multiple asynchronous operations concurrently within one function scope.
  • Each async let binding must be awaited to retrieve its value.
  • Task groups (withTaskGroup) manage a dynamic number of concurrent child tasks together.
  • Structured concurrency ties a task's lifetime to the scope that created it, making cancellation and error handling predictable.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.