Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 146 ยท Concurrency

Actors

Learn Swift actors - how they protect mutable state, actor isolation, why you need await, reentrancy bugs, nonisolated members, isolated parameters, global actors and @MainActor in main.swift.

Concurrency has one famous trap: two pieces of code change the same data at the same time. Classes cannot protect you from it. As soon as two tasks hold a reference to the same object, they can both write to it, and the result is a data race: lost updates, corrupted collections, crashes that only happen on Friday afternoons. Swift 6 makes such code a compile error, and the actor is the main tool it gives you to write the code correctly.

An actor is a reference type, like a class, with one extra promise: only one task at a time can run code that touches its mutable state. Other tasks politely wait their turn. This lesson explains how that works, what await means when you call an actor, the one subtle trap called reentrancy, and how global actors such as @MainActor extend the idea. It follows Task groups and leads into Sendable.

The problem actors solve

Here is the classic broken counter. Many tasks each add one to a shared class instance.

Swift A class shared 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 diagnostic is main.swift:10:25: 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. In plain words: the compiler sees that a mutable class instance is about to be shared between tasks without any protection, and it stops you. In older Swift versions this program compiled and could print a number below 100.

The fix is to change one word:

Swift The same counter as an actor

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.

It always prints 100. Two things changed: class became actor, and every use from outside got an await. The actor guarantees that the 100 calls to increment() run one after another, never overlapping.

How an actor works

Think of an actor as a small office with a single desk. Visitors (tasks) line up outside. Only one visitor is at the desk at a time, and that visitor may read and change the papers (the actor's properties). When the visitor leaves, the next one enters. Nobody ever sees the papers half-edited.

The technical name is actor isolation. An actor's stored properties and its methods are isolated to the actor:

  • Code inside the actor (its own methods) can use the properties directly, with no await.
  • Code outside the actor has to ask. A call is implicitly asynchronous, so it needs await, because the caller may have to wait until the actor is free.

Try to skip the await and you get a compile error, not a data race:

Swift Reading an actor property without await (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 real message is main.swift:7:15: error: actor-isolated property 'value' can not be referenced from the main actor. Calling counter.increment() without await fails in a similar way: call to actor-isolated instance method 'increment()' in a synchronous main actor-isolated context, with a note that such calls "are implicitly asynchronous". The fix in both cases is await: print(await counter.value).

Every await on an actor is a suspension point: your task is paused, the thread is free to run other work, and your task resumes later when the actor is available. That is cheaper than blocking a thread on a lock, and it is why actors fit naturally with async/await.

Actors are reference types

Like a class, an actor is a reference type. Copying the variable copies the reference, so all copies talk to the same actor. Unlike a class, an actor does not support inheritance (there is no class Sub: SomeActor), and it is automatically Sendable, which means you may pass a reference to it between tasks freely. That is exactly what the task group above did.

Swift Two names, one actor

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 output is ana=15, ben=7 and true. The operator === (identity) works on actors just as on classes. Note that summary() lives inside the actor, so it reads scores without any await, and it sorts the keys because a dictionary has no stable order.

What can be inside an actor

Everything you can put in a class goes in an actor: stored and computed properties, methods, initializers, subscripts, and protocol conformances. A few rules are special.

Initializers. An actor's init runs before the actor exists as a shared object, so it can set properties freely and is not isolated like a method. Nobody else can hold a reference yet.

Constants. A let property of a Sendable type can never change, so reading it cannot race. You can read it from outside with no await:

Swift let properties and nonisolated members

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.

Expected output: A-17, account A-17, Account(A-17), then 15. The keyword nonisolated removes a member from the actor's protection, which means it can be called from anywhere, synchronously, and therefore can only use things that are safe to read from anywhere. If it touches mutable state, the compiler objects:

Swift nonisolated reading mutable 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.

You get main.swift:3:47: error: actor-isolated property 'balance' can not be referenced from a nonisolated context. This is the compiler doing its job: reading balance from outside the actor could race with a writer.

The most common reason to write nonisolated is a protocol requirement that is not async, such as CustomStringConvertible, Hashable or Equatable. Build those from let properties only (like id above).

Reentrancy: the trap inside the actor

An actor runs one task at a time, but that does not mean a method runs from start to finish without interruption. When a method hits an await on something else, it suspends, and the actor becomes free to run another call. When the first call resumes later, the state may have changed in between. This is called actor reentrancy.

Take a wallet whose spend method checks the balance, does something asynchronous (writing an audit record), and then subtracts:

Swift A reentrancy bug

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.

Both calls succeed and the balance ends at -60. Here is what happened: the first call checks (100 is enough for 80), reaches the sleep, and suspends. The actor is free, so the second call starts, also checks (the balance is still 100), and also suspends. Both then resume and subtract. There is no data race, because only one piece of code touched balance at a time, but there is a logic race: the check and the change were separated by an await.

The cure is a simple rule: do your checking and changing without an await in between, or check again after resuming. The best fix here is to change the state first, before suspending:

Swift Fix: change the state before suspending

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.

Now exactly one call wins. The output is [true, false] and balance: 20. The synchronous stretch from the guard to the subtraction cannot be interrupted, so it is atomic.

Reentrancy is the number one source of bugs in actor code. Whenever a method of an actor contains await, assume that any state you read before the await may be different after it. Keep invariant-protecting code in synchronous stretches, or re-validate after each await.

Reentrancy also explains another common surprise: the same slow work can run twice. This cache loads a value if it is missing, and the load takes time:

Swift Two callers, two loads

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.

Both callers print SWIFT, but loads is 2: the second caller arrived while the first was still loading, saw no entry, and started its own load. A later call is served from the cache, and loads stays at 2. To avoid the duplicate work, store the in-flight Task in the dictionary instead of the finished value, so later callers can await the same task. That pattern appears in Cancellation and Timeouts and in the async pipeline project.

Isolated parameters: many steps, one hop

Each await counter.increment() is a separate hop into the actor. If you need several operations to run as one uninterrupted block, you have two options: write a method on the actor, or write a function with an isolated parameter. Such a function runs on the actor, so it can use the actor's state directly.

Swift Using an isolated parameter

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 program prints ["== report ==", "generated", "== end =="] and then 3. The function writeHeader is not an actor method, but because its parameter is marked isolated, it is treated as running inside that actor. Callers still need await, once, for the whole function. You will see this style when you want an atomic multi-step update without adding a method for every combination.

Global actors and @MainActor

Sometimes the state you must protect is not inside one object but spread across many types, such as everything that touches the screen. A global actor is an actor with a single shared instance that you can attach to types, functions and properties with an attribute. The built-in one is @MainActor, which represents the main thread. You can also define your own:

Swift A custom global actor

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.

Everything marked @DatabaseActor shares one isolation domain, so seed can call store.add without await. Callers outside need await. The program prints ["one", "two"].

Top-level code in main.swift

There is one place where a global actor is quietly in charge: the top-level code of main.swift, which every program on this site uses. Top-level variables in main.swift are implicitly @MainActor, and so is the top-level code that uses them. That is why error messages in this track say "main actor-isolated". It also means this tiny program is rejected:

Swift Touching a main-actor variable from another task (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 real message is main.swift:2:15: error: main actor-isolated var 'counter' can not be mutated from a nonisolated context, with a note offering to add @MainActor to bump(). Task.detached starts a task that is not on the main actor, so it cannot touch main-actor state without await. There are three honest fixes: put the state in an actor, keep all the access on the main actor (mark bump with @MainActor and await it), or pass the data in and return it instead of sharing it.

In an app with a user interface, @MainActor is how you say "this must run on the main thread": view models and anything that updates the screen are @MainActor. In the command-line programs you run in this tutorial, @MainActor mostly shows up as the default isolation of top-level code. The Tasks lesson explains how a plain Task { } inherits that isolation.

Actors, locks and other tools

Situation Good tool
Shared mutable state used by async code actor
Immutable data shared between tasks A struct or let of Sendable type
A tiny critical section in synchronous code Mutex (Synchronization and Shared State)
State tied to the UI thread @MainActor
One task owns the data and passes it on Pass values, no sharing needed

Actors are not free. Each call from outside is a possible suspension, and a very busy actor can become a bottleneck because everything queues at its single desk. If a hot path only needs to bump a counter, a Mutex or an atomic can be faster. If an actor has a long synchronous method, every other caller waits for it. Keep work inside actors short, and do slow computation outside, passing results in.

Common mistakes

  • Assuming await inside an actor method keeps the state frozen. It does not; see reentrancy above.
  • Putting everything in one giant actor. It serializes unrelated work. Use small actors with a clear job.
  • Returning a mutable class instance from an actor method. The caller can then change it outside the actor's protection. Return value types or other Sendable things.
  • Using nonisolated to silence an error. It only fixes code that really needs no isolation.
  • Expecting actor calls to be handled in first-come order. Do not rely on a strict order between calls from different tasks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an actor guarantee?

    An actor serializes access to its isolated state. It does not use the main thread (that is @MainActor) and calls from outside need await.
  2. 2. Why does print(counter.value) fail to compile when counter is an actor instance and value is a var?

    From outside, access to isolated state may have to wait for the actor, so it must be written await counter.value.
  3. 3. A method of an actor checks balance >= amount, then awaits a sleep, then subtracts. Two calls run together. What can go wrong?

    An await inside an actor method is a suspension point, and the actor may run other calls meanwhile. Do the check and the change without an await in between.
  4. 4. When can a member of an actor be marked nonisolated safely?

    A nonisolated member can run from anywhere at the same time, so it must not read or write the actor's mutable state.
  5. 5. In the top-level code of main.swift, what is the isolation of a global var?

    Top-level variables in main.swift are implicitly @MainActor. That is why other tasks need await (or an actor) to touch them.

Summary

  • An actor is a reference type that serializes access to its mutable state, which removes data races without manual locks.
  • From outside the actor, access to isolated properties and methods is asynchronous and needs await; inside, no await is needed.
  • let properties of Sendable types and nonisolated members can be used without await, but nonisolated members must not touch mutable state.
  • await inside an actor method is a suspension point: other calls can run, so state may change (reentrancy). Check and change in one synchronous stretch, or re-check after resuming.
  • An isolated parameter lets a function run on an actor and do several steps in one hop.
  • Global actors such as @MainActor (and your own @globalActor types) share one isolation domain across many declarations; top-level code in main.swift is on the main actor.
  • Keep actors small and their synchronous work short, and prefer passing values over sharing.

Next: Sendable and Data Races explains which values may cross between tasks and actors.