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.
In this page:
Starting a Task
Task { } launches a new block of asynchronous work immediately, which can itself contain await calls.
Example: Starting a Task
func computeSquare(_ n: Int) async -> Int {
return n * n
}
let task = Task {
return await computeSquare(6)
}
let result = await task.value
print("Square: \(result)")
Login to try C/C++/Java/PHP code in the editor
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
let task = Task { () -> String in
return "Task finished"
}
let outcome = await task.value
print(outcome)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that code inside a
Task { }closure runs asynchronously and may not have finished by the next line after it. - Trying to
awaitaTask's result without accessing its.valueproperty. - Creating many unstructured
Task { }instances when a structured concurrency construct likeasync letor a task group would be safer and easier to manage.
Chapter Summary
Task { }starts a new unit of asynchronous work.- A
Task's.valueproperty 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: