🎓 A1Learner
🔍
0 of 27 lessons completed

Swift Tasks

A task is a handle for work that runs concurrently with the rest of a program. The program can read the finished value through the handle or ask whether the handle was cancelled.

A task handle and its value

The handle holds work that returns a number. Reading value with await waits for that work and gives back 42.

let task = Task {
    return 42
}
let result = await task.value
print(result)

Two handles read in order

Each handle holds a piece of work that returns a word. The program reads the values in a fixed order, so the prints follow that order.

let first = Task {
    return "first"
}
let second = Task {
    return "second"
}
let firstResult = await first.value
let secondResult = await second.value
print(firstResult)
print(secondResult)

A detached task

The detached task runs separate from the code that created it. Its handle still gives back the finished value through value.

let task = Task.detached {
    return 7 * 6
}
let result = await task.value
print(result)

Cancelling a handle

The cancel call marks the handle as cancelled. The print then reads isCancelled on the handle and shows true.

let task = Task {
    return 10
}
task.cancel()
print(task.isCancelled)

Example

let task = Task {
    var sum = 0
    for n in 1...4 {
        sum += n
    }
    return sum
}
let total = await task.value
print(total)

Key points

  • A task handle is created with the Task name and a trailing closure.
  • Reading value with await waits for the work and gives back its result.
  • Two handles can hold two pieces of work at the same time.
  • Reading the values in a chosen order prints them in that same order.
  • A detached task runs separate from the work that created it.
  • The cancel call marks a handle as cancelled.
  • The isCancelled property reports whether cancel was called on the handle.

In this example, the task adds the numbers from 1 to 4 inside its closure. The program waits for the handle through value. The print shows the finished sum of 10.

Note

the cancellation program in this lesson reads isCancelled right after cancel so the printed result never changes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

After cancel is called on a handle, what does isCancelled read?