10.9 · Isolation rules, isolated parameters, global actors, main-actor hops and default isolation
Actors are easy to describe and fiddly to use. This section is about what the compiler allows, where code really runs after an await, and how the newer defaults change it.
Mental model. Isolation is a property the compiler tracks: crossing it needs an await; staying inside it does not; and where code executes follows from which isolation the function has.
What the compiler allows
Access rules, nonisolated, isolated parameters and global actors.
- Which accesses to an actor compile without await, which do not compile at all, and what do nonisolated members change?
From outside an actor, you may call its methods and read its state only asynchronously. Reading a.balance from a different isolation is a compile error… - What is an isolated parameter, and when would you write a function that takes one instead of making it an actor method?
An isolated parameter says “this function runs on that actor, for the whole call”. Inside bump(_ a: isolated Account) you can read and write a.balance directly… - How do you define your own global actor, what does annotating a type with it do, and when is it better than an actor instance or the main actor?
A global actor is an actor with a static let shared instance, marked @globalActor. Annotating a function, property, or whole type with @Store makes all its…
Where code runs
Main-actor hops, nonisolated async functions, and default isolation.
- Where does code actually run after an await: what do @MainActor, MainActor.run and a nonisolated async function guarantee about the thread?
Isolation decides where code executes. A @MainActor function always runs on the main thread, however it is called: the check prints main=true for it, both when… - What does the Swift 6.2 default actor isolation setting change, and how does it affect a global variable or function you call from a background task?
By default (and in Swift 6 language mode) code in a module is nonisolated unless you annotate it, so shared mutable state needs explicit protection. Swift 6.2…
More in Concurrency
- 10.1 · Queues, QoS, barriers, groups, semaphores and sources
- 10.2 · Operation, OperationQueue, dependencies and cancellation
- 10.3 · async/await, tasks, task groups, cancellation and task locals
- 10.4 · Actors, reentrancy, isolated, nonisolated, global actors and @MainActor
- 10.5 · Region-based isolation, sending, and migrating to Swift 6
- 10.6 · Continuations and bridging GCD, Combine and callback APIs
- 10.7 · Deadlocks, main-actor hops, Thread Sanitizer and Instruments
- 10.8 · Task groups, async let, cancellation and task locals in practice
- 10.10 · Sendable rules, locks versus actors, and the escape hatches
- 10.11 · Groups, semaphores, parallel loops, operation dependencies, QoS and timers
- 10.12 · AsyncStream buffering, continuation misuse and notifications as async sequences