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

Task Basics

A Task is a little unit of work you kick off that runs on its own, letting your program start it and move on.

Starting a Task

Task { } launches a new block of asynchronous work immediately, which can itself contain await calls.

Example: Starting a Task

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

let task = Task {
    return await computeSquare(6)
}
let result = await task.value
print("Square: \(result)")

Awaiting a Task's Value

A Task's .value property suspends until the task completes and then yields its result, letting you retrieve the outcome of the concurrent work.

Example: Awaiting a Task's Value

markup
let task = Task { () -> String in
    return "Task finished"
}
let outcome = await task.value
print(outcome)
Common Mistakes
  1. Forgetting that code inside a Task { } closure runs asynchronously and may not have finished by the next line after it.
  2. Trying to await a Task's result without accessing its .value property.
  3. Creating many unstructured Task { } instances when a structured concurrency construct like async let or a task group would be safer and easier to manage.
Chapter Summary
  • Task { } starts a new unit of asynchronous work.
  • A Task's .value property can be awaited to retrieve its eventual result.
  • Tasks inherit priority and context from where they're created, but run independently.
  • Unstructured tasks are simple but structured concurrency (task groups, async let) is often preferred for related work.
🔒

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.