Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 146 ยท Concurrency

Introduction to Swift Concurrency

A beginner-friendly tour of Swift concurrency: why async/await replaced callbacks, what tasks are, how await suspends, and how Sendable prevents data races in Swift 6.

Programs rarely do one thing and nothing else. They download data, wait for a database, read files, and respond to a user, all at once. If your code simply stops and waits for each slow operation, everything else stops too. Concurrency is the set of tools for making progress on several things at the same time, or at least for not freezing while you wait.

Swift has a built-in model for this, introduced in Swift 5.5 and made much safer in Swift 6. It is based on three ideas you will meet in the next lessons: async/await for writing waiting code that reads top to bottom, tasks for running work, and data-race safety checked by the compiler. This lesson is the map. You will see the problem, the old solution, the new one, and the vocabulary you need before going deeper into async and await, tasks, actors and Sendable.

Waiting is the problem

Think of a cook who puts a pot of water on the stove. The sensible cook does not stare at the pot for ten minutes. While it heats, they chop vegetables. In programming terms, "waiting for water" is a slow operation (network, disk, timer), and "chopping" is other useful work.

Code that blocks, meaning it sits and does nothing until the slow operation finishes, wastes time and, in an app with a screen, freezes the interface. Good code should let other work happen during the wait. The question is how to write that without making the program a tangle.

Two words are often confused:

  • Concurrency is about structure: several tasks in progress, taking turns or overlapping.
  • Parallelism is about hardware: two things literally running at the same instant on different CPU cores.

You can have concurrency on a single core (tasks take turns). The runner on this site has one CPU, so the examples here show concurrency, not speed-ups. The code you write is the same either way.

The old way: callbacks

Before async/await, you handled waiting with completion handlers: you passed a closure that the function would call when the result was ready. Here is a tiny, deterministic imitation. Each function calls its handler right away, to keep the output predictable, but the shape of the code is what matters.

Swift Callbacks nest deeper with every step

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.

Three steps, three levels of indentation, and the error handling repeated each time. This is sometimes called the pyramid of doom. It also has quieter problems: nothing forces a function to call its completion handler exactly once, return does not mean what you expect (the real result arrives somewhere else), and throw does not work across callbacks. Bugs hide easily.

The new way: async and await

Swift lets you mark a function async, which means "this function may need to wait". Callers use await at each call that might wait. The code then reads in order, uses normal return, throw and try, and has no pyramid.

Swift The same three steps with async and await

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.

That is the whole program for the same job, with the error handling written once. Notice three things. A function that waits is marked async (and throws if it can fail; try await is written in that order). Every call to an async function is marked await, so you can see exactly where the code may pause. And in main.swift you can write await at the top level, so you can start the whole thing without extra ceremony.

What await really does

await is a suspension point. When your code reaches it, the function may be paused, and the thread it was running on is free to do other work. When the awaited call finishes, your function resumes, possibly on a different thread, and continues from where it left off. No thread sits idle, which is why you can have thousands of waiting tasks without thousands of threads.

Two consequences matter right away:

  1. Code between two awaits runs without interruption by your own task, but anything else in the program may run at each await. State you read before an await may have changed after it. You will see this again with actors (it is called reentrancy).
  2. You can only write await inside an async context: an async function, a Task, or top-level code in main.swift. A normal synchronous function cannot await. The compiler enforces it.
Swift await outside an async context (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 stops with main.swift:6:23: error: 'async' call in a function that does not support concurrency, with a note suggesting you add async to plainFunction(). The fix is either to mark plainFunction as async (and await it) or to start a Task from it, which is the next idea.

Tasks: units of work

A task is a unit of asynchronous work that the runtime schedules for you. Every async function runs inside some task. You create new tasks in a few ways, which later lessons cover in depth:

  • Task { ... } starts new work from synchronous code, and it begins running on its own.
  • async let starts a child task for one value and lets you wait for it later.
  • Task groups create a dynamic number of child tasks.

The simplest demonstration is async let, which runs several pieces of work at the same time and collects the answers.

Swift Starting work together with async let

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.

Each slowSquare sleeps for 100 milliseconds. Awaiting them one after another would take about 300 ms. With async let, all three sleeps overlap, so the whole thing takes roughly 100 ms. The comparison against 250 ms prints a verdict without showing an exact time, because timings vary from run to run. Sleeping does not need a CPU, which is why this overlap works even on one core: the tasks are waiting, not computing.

Task.sleep also shows the modern API style: Task.sleep(for: .milliseconds(100)) uses the Duration type, and it is a cancellable suspension point.

Starting a Task from ordinary code

Most apps have plenty of synchronous code, for example an event handler. To call async code from there, create a Task. The task runs independently, so the synchronous function returns immediately.

Swift Task { } bridges synchronous code to async code

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 lines print as 1, 2, 3, 4. buttonTapped prints its own two lines and returns before the task finishes. The task completes later, and the final sleep in main.swift gives it time to do so. Without that wait, the program could end before the task ran. In real apps something else keeps the program alive (an event loop, a server). A better way to wait for a task is to await its value; the tasks lesson shows how.

Why Swift 6 cares about data races

A data race happens when two pieces of code touch the same memory at the same time and at least one of them writes. The result is unpredictable: wrong totals, corrupted data, crashes that appear only once in a thousand runs. These are some of the hardest bugs in all of programming.

Swift 6 turns this class of bug into compile-time errors. Every value that crosses from one concurrent task to another must be safe to share. A type declares this by conforming to the marker protocol Sendable. Value types made of Sendable parts (like Int, String, and structs of them) are Sendable automatically. A plain class with mutable properties is not.

Swift Sharing a mutable class between tasks (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.

Swift 6 refuses to build this. The first error reads main.swift:8:5: error: non-Sendable type 'Counter' of let 'counter' cannot exit main actor-isolated context, with a note that class Counter does not conform to the Sendable protocol. A second error says the main actor-isolated let counter cannot be accessed from outside of the actor. Both say the same thing: top-level variables belong to the main actor, and a detached task runs somewhere else, at the same time as other code that also uses counter. The fixes are the subject of later lessons: make the type a value type, make it an actor so access is serialized, protect it with a Mutex, or confine it to one actor like @MainActor.

The mental model to keep: sharing mutable state between tasks needs a safe owner. Actors are those owners, and Sendable is how the compiler checks that only safe things travel between them.

A first look at actors

An actor is a reference type that protects its own state: only one task at a time can run its code, and callers use await to get in line. Here is a tiny preview, with full coverage in Actors.

Swift An actor protects its state

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.

A hundred tasks all increment the same counter, and the answer is always exactly 100, with no data race and no lock written by you. The await on counter.increment() is the price: a call into an actor from outside may have to wait its turn.

Where does my code run?

A last piece of vocabulary: isolation. Code is either isolated to some actor (and runs only on that actor's "serial executor") or it is not. The main actor, written @MainActor, is the special actor that represents the main thread, where user interface code must run. Top-level code in main.swift is implicitly on the main actor, which is why a plain Task { } written there inherits that isolation. For a command-line program this matters little. In UI apps it is central, and we cover it in Actors.

The older tools still exist: threads, DispatchQueue, locks. They remain useful for interoperability, and you can read about them in Threads and Dispatch. For new code, prefer async/await, tasks and actors, and let the compiler help.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the await keyword mark?

    await marks a suspension point. The function can pause there and resume later, while the thread does other work.
  2. 2. What is the main advantage of async/await over completion-handler callbacks?

    Async code avoids nested closures and lets you use the regular control flow of the language.
  3. 3. How do you call an async function from ordinary synchronous code?

    await is only allowed in an async context. Task { } creates one from synchronous code.
  4. 4. Why does Task.detached { counter.value += 1 } fail to compile in Swift 6 when counter is an instance of a plain mutable class?

    A closure passed to a detached task must be Sendable. A non-Sendable class instance captured by it could be accessed from two tasks at once.
  5. 5. What is the difference between concurrency and parallelism?

    Concurrency lets several tasks make progress, even on one core. Parallelism means true simultaneous execution.

Summary

  • Concurrency lets a program make progress while waiting on slow operations; parallelism is the hardware-level cousin.
  • Completion-handler callbacks nest deeply and make error handling repetitive; async/await replaces them with straight-line code.
  • Mark waiting functions async; mark each call to them with await; write try await for throwing ones.
  • await is a suspension point where other work may run; it is only allowed in an async context.
  • Tasks are units of asynchronous work: Task { }, async let and task groups create them.
  • Swift 6 detects data races at compile time; values that cross between tasks must be Sendable.
  • Actors protect mutable state by letting one task at a time in; @MainActor is the actor for the main thread.

Next: async and await