Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 146 ยท Concurrency

Tasks

Learn how Swift Tasks work: creating them, awaiting their value or result, priorities, detached tasks, actor inheritance, cooperative cancellation and Task.sleep.

Every piece of asynchronous Swift code runs inside a task. You have already met tasks indirectly: async let creates a child task, and Task { } starts new work from ordinary code. This lesson looks at tasks directly. You will learn how to create one, how to get its answer back, how to stop it, and what "detached" means. It builds on async and await and prepares the ground for task groups and cancellation.

Think of a task as a lightweight worker with a to-do list of one job. Creating a task is cheap (much cheaper than a thread), so programs routinely have thousands of them. The runtime decides which threads actually run them.

Creating a task and reading its value

Task { ... } starts a new task and hands you a handle: a value of type Task<Success, Failure>. The closure's return value is the task's result. You get it with await task.value.

Swift A task is a handle to a result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The type of task here is Task<Int, Never>: it produces an Int, and Never says it cannot fail. The task starts on its own as soon as it is created. await task.value waits until it is done (or returns straight away if it already finished) and gives you the result. You can await the same handle many times, and every await sees the same value.

Tasks that throw

If the closure can throw, the task's failure type becomes any Error, and reading the value needs try. You can also ask for the outcome as a Result with .result, which never throws and is handy when you want to handle both cases in one place (see The Result Type).

Swift Throwing tasks and the result property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first await prints page 1; the second throws, so the catch runs. The .result property gives the same information as a value you can switch over, and does not need try.

Tasks keep running when you drop the handle

A task created with Task { } is unstructured: it is not tied to the scope that created it. If you ignore the handle, the task still runs to the end. This is useful for "fire and forget" work, but it also means nothing waits for it automatically. Contrast that with async let, whose child is awaited at scope exit.

Swift Fire and forget: nothing waits for you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two synchronous lines come first, then the background line, then main exits. If main had exited sooner, the process would have ended and the background task would have been cut off. For work that must finish, keep the handle and await it.

Where does a task run? Inheritance and detached tasks

Task { } inherits its context from the code that creates it: the actor isolation, the priority, and task-local values. Code in main.swift is isolated to the main actor, so a plain Task { } written there can read and change top-level variables safely. It runs on the main actor, one piece at a time.

Task.detached { } makes a task with no inherited context. It does not belong to any actor and it takes no priority from you. That is exactly why the compiler is stricter: a detached task could run at the same time as the code that created it.

Swift A detached task cannot touch main-actor state (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports main.swift:4:5: error: main actor-isolated var 'counter' can not be mutated from a nonisolated context, plus a note that mutation of this var is only permitted within the actor. The variable counter lives on the main actor, and the detached task is somewhere else. The easiest fix is the simplest idea: return the result instead of mutating shared state.

Swift The fix: return a value from the task

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The detached task computes and returns 1. The main code adds it to the counter after awaiting. The second task inherits main-actor isolation, so it may change counter directly; it is not running at the same time as other main-actor code, because the main actor runs one thing at a time.

Prefer a plain Task { } or structured concurrency (async let, task groups). Reach for Task.detached only when you really want to leave the current actor, for example to do heavy computation away from the main actor. Detached tasks drop priority and actor context, and are easier to misuse.

Priorities

A task has a priority that hints to the runtime how urgent it is: .high (also .userInitiated), .medium, .low (also .utility) and .background. A task created without one takes the priority of its creator, and Task.currentPriority tells you what you have.

Swift Setting and reading task priority

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Priority is advice, not a guarantee. It helps the scheduler pick which waiting task to run first when several are ready. It does not make code faster by itself, and if a high-priority task waits on a low-priority one, the runtime may temporarily boost the low one (priority escalation). Do not build logic that depends on the order tasks start.

Cancellation is cooperative

You stop a task by calling cancel() on its handle. This does not kill the task. It only sets a flag. The task has to check the flag and stop on its own, which is why Swift calls cancellation cooperative. Many standard async functions check for you: Task.sleep throws CancellationError when its task is cancelled, and so do many library calls.

Swift Cancelling a task that is sleeping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because sleeper.cancel() runs before the task gets its first turn on the main actor, the task sees isCancelled already true, and the 10-second sleep ends immediately with a CancellationError instead of waiting. You do not wait ten seconds.

Your own long-running code must check. There are two ways inside a task: Task.isCancelled (a Bool you can inspect and clean up after) and try Task.checkCancellation() (throws CancellationError for you). Here is a loop that stops cleanly:

Swift A loop that honors cancellation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Task.yield() gives other tasks a chance to run; it is also a convenient place for a task to notice that it was cancelled. The first run counts to 5. The cancelled run reports cancelled after 0 and returns 0, because the flag was set before the loop began.

Two rules to remember:

  • Cancelling a task cancels its child tasks (async let and task groups) too, but not unstructured tasks it created with Task { }.
  • A cancelled task is still allowed to finish its work and return a value. Cancellation is a request. Decide in your code whether to return early, throw, or return partial results. More patterns are in Cancellation and Timeouts.

Running many tasks and collecting the results

You can create tasks in a loop, store the handles in an array, and then await them. Awaiting in array order gives results in a predictable order, even if the tasks finish in a different order.

Swift Starting several tasks and gathering results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The "computed" lines appear in the order the delays end (4, 5, 3), but results is [9, 16, 25], because we awaited the handles in the order we stored them. This is fine for a fixed list. For a dynamic number of tasks and tidy error handling, task groups are the better tool.

Common mistakes

  • Forgetting that unstructured tasks outlive their scope. If you need the work to finish, keep the handle and await it.
  • Using Task.detached by default. It removes actor protection and loses the creator's priority. Use it on purpose.
  • Ignoring cancellation in loops. A long loop without Task.isCancelled or checkCancellation() cannot be stopped.
  • Mutating shared variables from several tasks. Swift 6 stops this at compile time; return values or use an actor.
  • Treating priority as ordering. It is a hint, never a promise of the order of execution.
  • Blocking inside a task. Thread.sleep or a semaphore blocks a worker thread; use await Task.sleep(for:) and other async APIs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What type does Task { 21 * 2 } produce, and how do you read its result?

    The closure returns an Int and cannot throw, so the handle is Task<Int, Never>. You await its value property.
  2. 2. What does task.cancel() do?

    Cancellation is cooperative. The task decides how to react, and Task.sleep throws CancellationError for you.
  3. 3. What is the key difference between Task { } and Task.detached { }?

    Inheritance is the difference. Detached tasks start with a clean context, which is why Swift 6 checks what they capture more strictly.
  4. 4. You call Task { ... } and ignore the returned handle. What happens to the task?

    Unstructured tasks are not tied to the creating scope. They keep running, so keep the handle if you need to wait.
  5. 5. Which statement about task priority is true?

    Priority only influences scheduling. Never rely on it to order your program's logic.

Summary

  • Task { } starts work and returns a handle Task<Success, Failure>; read the result with await task.value (or try await if it throws), or with await task.result.
  • Unstructured tasks keep running even if you drop the handle; keep the handle when you need to wait.
  • A plain Task inherits actor isolation, priority and task-local values; Task.detached inherits nothing and is checked more strictly in Swift 6.
  • Prefer returning values from tasks to mutating shared variables.
  • Priorities (.high, .medium, .low, .background) are scheduling hints only.
  • cancel() sets a flag; tasks cooperate by checking Task.isCancelled or calling try Task.checkCancellation(), and Task.sleep throws when cancelled.
  • Cancelling a task also cancels its structured children (async let, task groups).

Next: Task Groups