In Swift, what changes when a shared thumbnail cache is declared as an `actor` rather than a class, and why must callers write `await`?
answer
- one task at a time on its state
- isolation checked at compile time
- outside calls may suspend
- reference type without subclassing
basics
~20 sAn actor is a reference type whose mutable state only its own code can touch, one task at a time. Outside code reaches that state through asynchronous calls, marked with await because the caller may have to wait.
solid answer
~40 sDeclaring `actor ThumbnailCache` keeps reference semantics, so every screen shares one instance, but its stored properties and methods become **actor-isolated**: only code running on that actor touches them, and the actor runs one piece of code at a time, so the dictionary never sees two concurrent writers and needs no lock. The compiler enforces it. From outside, `cache.image(for:)` is a cross-actor call, written `await cache.image(for: url)` even though the method is synchronous inside the actor, because the caller may wait for the actor. Outside code cannot assign an isolated property even with `await`; it calls a method. A `let` of a `Sendable` type can be read without `await`, but only from the same module. Actors also give up inheritance: no superclass, no subclass, no `override`.
code
swift · 24 linesimport Foundation
actor ThumbnailCache {
let capacity: Int
private var images: [URL: Data] = [:]
init(capacity: Int) { self.capacity = capacity }
func image(for url: URL) -> Data? { images[url] }
func store(_ data: Data, for url: URL) {
if images.count >= capacity { images.removeAll() }
images[url] = data
}
}
func showThumbnail(from cache: ThumbnailCache, url: URL) async {
let limit = cache.capacity // same-module Sendable let: no await
if let data = await cache.image(for: url) { // cross-actor call: await
print("hit, \(data.count) bytes, limit \(limit)")
} else {
await cache.store(Data(), for: url)
}
}go deeper
Recall that an actor is a reference type whose state only its own code touches, and that calls from outside are written with await.
Explain cross-actor references: why a synchronous method becomes asynchronous from outside, why outside assignment is rejected, and the same-module Sendable let exception.
Show where actor isolation ends: it serializes access but not a whole method across its own awaits, and API design should expose operations rather than raw mutable properties.
Weigh the cost of turning a shared class into an actor: every outside call site becomes async, which spreads await through the codebase and changes how modules expose the type.
## What the `actor` keyword declares An **actor** is a nominal type, like a class, struct or enum, introduced with the `actor` keyword. It can have stored and computed properties, methods, initializers, subscripts, extensions and protocol conformances. Like a class it is a **reference type**: when the gallery screen and the detail screen both hold a `ThumbnailCache`, they hold the same instance. Unlike a class, an actor protects its mutable state with **actor isolation**: the state belongs to the actor, and only code running *on* that actor may read or write it. The Swift book states the run-time side of the guarantee: an actor allows only one task at a time to access its mutable state. Requests from other tasks wait their turn. For a cache, that means two screens that store thumbnails at the same moment can never corrupt the dictionary, and you write no lock, queue or semaphore. ## What the compiler checks Isolation is enforced at compile time. Every reference to an actor-isolated member from outside the actor is a **cross-actor reference**, and Swift allows it in only two ways: - as an **asynchronous call**, written with `await`, which may suspend the caller until the actor can run the request; - as a read of an immutable `let` whose type is `Sendable`, from code in the **same module**; another module must still write `await`, so the defining module stays free to turn that `let` into a `var` later without breaking clients. | Access from outside the actor | Swift 6.4 verdict | |---|---| | `cache.image(for: url)` in a synchronous nonisolated function | error: "call to actor-isolated instance method 'image(for:)' in a synchronous nonisolated context" | | `cache.image(for: url)` in an `async` function, without `await` | error: "actor-isolated instance method 'image(for:)' cannot be called from outside of the actor" | | `await cache.image(for: url)` in an `async` function | allowed | | assigning an isolated `var` from outside, with or without `await` | error: the property "can not be mutated from a nonisolated context" | | reading `cache.capacity` (a `Sendable` `let`) in the same module | allowed without `await` | | the same read from another module | needs `await` | These are errors in both the Swift 5 and Swift 6 language modes: actor isolation itself has been enforced since actors arrived in Swift 5.5. What Swift 6 mode adds is stricter checking of the *values* that cross into and out of the actor, which is the subject of the lesson on Sendable and data-race safety. ## Why `await` appears on a synchronous method Inside the actor, `image(for:)` is an ordinary synchronous method, and the actor's own code calls it without `await`. From outside, the call is turned into a request that the actor runs when it is free. The caller may have to wait, so the call is asynchronous for the caller and Swift requires `await` to mark that **possible suspension point**. Two consequences follow: 1. A synchronous function outside the actor cannot call the method at all; it has no way to suspend. It must become `async`, or start a `Task`. 2. Writing `await` does not promise a thread switch or a delay. If the actor is free, the request may run at once; `await` marks only that suspension is *possible*. Assigning a property from outside is rejected even with `await`, because an asynchronous set would let two properties that must change together drift apart, and an `inout` access across a suspension cannot be made safe. The actor exposes a method such as `store(_:for:)` instead, so it keeps control of its invariants, for instance evicting entries when the cache reaches capacity. ## Actor or class: what else changes | | `final class` cache | `actor` cache | |---|---|---| | Semantics | reference | reference | | Concurrent mutation | your job (lock, queue) | prevented by isolation | | Calls from outside | synchronous | `await`, except same-module `Sendable` `let` | | Inheritance | yes, unless `final` | none: "actor types do not support inheritance" | | `override`, `class` members, `open`, `final`, `required`/`convenience` init | available | not applicable | What isolation does **not** promise is that a method runs from start to finish without other calls slipping in. When an actor method itself awaits, for example on a download, the actor can run other requests in the meantime; that is actor reentrancy, covered in its own lesson, and it is why state read before an `await` must be re-checked after it. ## Common mistakes - Treating `await` as "runs on a background thread": it marks a possible suspension, nothing more. - Expecting `await cache.images = [:]` to compile: outside code calls a method that does the assignment. - Making every property a public `var` and mutating it from callers, which defeats the point of isolating it. - Assuming a `let` is always readable without `await`: only from the same module, and only for a `Sendable` type.
- Why may code in the same module read the actor's `let capacity` without `await`, while another module may not?An immutable `let` of a `Sendable` type cannot change after initialization, so reading it races with nothing, and the compiler allows a synchronous read inside the defining module. Another module must still write `await`; that keeps the defining module free to evolve the `let` into a `var` without breaking clients. Swift 6.4 reports the missing `await` there as "actor-isolated property 'capacity' cannot be accessed from outside of the actor".
- Does `await cache.store(data, for: url)` mean the store runs on a background thread?It means the store runs on the cache actor, and the caller may suspend until it does. The book ties the main actor to the main thread; for an actor you declare, which thread runs its code is left to the runtime. What the caller can rely on is the isolation guarantee: no other code touches the cache's state while `store` runs.
- An actor is a value type, so each screen gets its own copy of the cache.
- Writing await before assigning an actor's property from outside makes it compile.
- await on an actor call always moves the work to a background thread.
- A synchronous function can call an actor method as long as it handles the result later.
- Actors can subclass each other like classes, with override.