skip to content

As a lead on a Swift app, how do you decide which shared state becomes an actor, which stays on the main actor, and which sits behind a `Mutex`?

level: principalimportance: should knowfreq 38%

answer

  1. who reads it, and how often
  2. does the critical section suspend
  3. await spreads to every caller
  4. hop cost versus lock cost
  5. Mutex needs a Swift 6.0 runtime

basics

~20 s

Keep state the UI reads on the main actor; make an actor for shared state whose operations are coarse, asynchronous and used from background work; use a Mutex for small synchronous critical sections that any context must call without await.

solid answer

~50 s

I start from who touches the state and whether its critical section suspends. State the UI renders stays `@MainActor`: one isolation domain, no hops from UI code, and background work hands results back. Shared mutable state used from background work, such as a thumbnail cache, a download coordinator or a database handle, becomes an `actor` when its operations are coarse and naturally `async`; I accept that every outside call becomes `await` and require invariants to change synchronously, because actors are reentrant. A `Mutex` from the Synchronization module (Swift 6.0, iOS 18 or later) fits a small synchronous section, such as a counter, an ID generator or a memo table, that must be callable without `await` from any context; its `withLock` body is synchronous, so it cannot suspend while holding the lock. The team rule: no actor per class, no lock around async work, and a review of chatty actor APIs.

code

swift · 29 lines
swift
import Synchronization

// UI-facing state: stays on the main actor.
@MainActor
final class GalleryViewModel {
    var thumbnails: [String: String] = [:]
}

// Shared async work with invariants across calls: an actor.
actor ThumbnailCache {
    private var stored: [String: String] = [:]
    func thumbnail(for name: String) async -> String {
        if let hit = stored[name] { return hit }
        let image = "thumb-\(name)"
        stored[name] = image
        return image
    }
}

// Tiny synchronous critical section callable from anywhere: a Mutex.
final class RequestCounter: Sendable {
    private let count = Mutex(0)
    func next() -> Int {
        count.withLock { value in
            value += 1
            return value
        }
    }
}

go deeper

for a junior

Recall the three options: main actor for UI state, actors for shared async state, Mutex for short synchronous sections.

for a middle

Explain how the tools differ for callers: await for both actors, a synchronous withLock for Mutex, and why withLock cannot suspend.

for a senior

Diagnose a design where actor hops or main-actor overload dominate, and move state or work to the tool that fits.

for a principal

Write and defend the team rule, weighing await propagation, reentrancy reviews, deployment targets and lock discipline for the codebase.

## Three tools, three guarantees Swift gives an app three standard ways to protect shared mutable state, and each makes a different promise to the code that uses it. | | `@MainActor` | `actor` | `Mutex` (Synchronization) | |---|---|---|---| | Isolation | one global domain, on the main thread | one domain per instance | none; a lock around one value | | Caller from elsewhere | `await` | `await` | synchronous `withLock` | | Can the protected code suspend? | yes, and others interleave | yes, and others interleave | no: the `withLock` body is synchronous | | Checked by the compiler | yes | yes | the `Mutex` itself is `Sendable`; correct use is up to you | | Availability | all supported releases | Swift 5.5 and later | Swift 6.0; iOS 18, macOS 15 or later | None of the three is free. The decision is about which cost fits the state. ## Questions to ask about each piece of state 1. **Who reads and writes it?** If it is mostly the UI, it belongs on the main actor; isolating it elsewhere makes every view update hop. 2. **Does an operation on it need to wait?** If an operation awaits I/O, only an actor can hold isolation across that wait; a lock cannot, and should not. 3. **How fine-grained are the calls?** An actor charges a possible suspension and an executor switch per outside call. Many tiny calls in a loop, such as reading one counter per pixel, make the hops dominate; a coarse API, or a `Mutex`, fits better. 4. **Must callers stay synchronous?** A logging call, a metrics counter or a delegate callback that cannot become `async` needs a synchronous tool: a `Mutex`, or the main actor if it already runs there. 5. **Which deployment targets ship?** `Mutex` needs the Swift 6.0 runtime; on older targets the alternative is a platform lock wrapped in a type that is declared `Sendable` by hand. ## Costs a lead must weigh - **`await` spreads.** Turning a class into an actor makes every caller outside it `async`, which can push `async` through layers that were synchronous. - **Reentrancy.** Actor code that awaits can see its own state change underneath it; reviews must check every `await` inside actor methods. - **Main-actor overload.** Putting everything on the main actor is the simplest model and right for most app state, but CPU-heavy work there, such as decoding thumbnails, stalls the UI; move such work into nonisolated `async` functions or an actor. - **Too many actors.** One actor per class turns simple calls into hops and splits invariants that span two objects into cross-actor sequences that can interleave. - **Lock discipline.** A `Mutex` is fast when uncontended and its critical sections are short; long sections, nested locks or calls back into unknown code bring back the deadlocks and contention actors were meant to remove. ## A rule a team can write down - UI state and view models are `@MainActor`; heavy work leaves the main actor explicitly. - An `actor` owns shared state with async operations and a coarse API; its methods change invariants synchronously and re-check state after each `await`. - A `Mutex` guards a small value with short synchronous operations that every context must call without `await`; nothing that suspends goes inside `withLock`. - Anything else needs a reason in review: a new actor, `nonisolated(unsafe)`, or `@unchecked Sendable`. ## Signals that a choice was wrong - Call sites full of `await` on an actor for values that never change: make them `nonisolated let` or move them out of the actor. - `MainActor.run` blocks scattered through background code: the operation probably belongs in a `@MainActor` method. - A `Mutex` whose closure grows to call into other objects: the state wants an owner, most likely an actor. - Dropped frames traced to main-actor work: move the computation off and keep only its result on the main actor. ## Where this meets neighbouring lessons Whether these types are `Sendable`, how a module adopts default main-actor isolation (Swift 6.2), and in what order a codebase moves to Swift 6 language mode are covered with Sendable and data-race safety. The actor model as a theory across languages, with mailboxes and supervision, belongs to the concurrency foundations. This question is about choosing among Swift's own tools for one app.

  • When would you split one large actor into several smaller ones?
    When unrelated state serializes behind one actor and calls queue up waiting for it, for example thumbnail lookups stuck behind slow metadata writes. Split only along a boundary with no shared invariant: once two actors must change together, the update becomes a sequence of cross-actor awaits that other calls can interleave, and the consistency the single actor gave you is gone.
  • Why not simply put all shared state on the main actor?
    For much of an app that is the right default: one isolation domain, no hops from UI code, and fewer reentrancy surprises. It fails when work on that state is CPU-heavy or frequent from background code, because everything on the main actor runs on the main thread and competes with rendering and input. Keep the state there, but move heavy computation off it and hand results back.

  • Every class that two features touch should become an actor.
  • A Mutex can be held across an await to protect an async operation.
  • Actors are always faster than locks because they avoid blocking.
  • Moving state to an actor removes the need to think about ordering.
  • Main-actor state cannot be updated from background work at all.

Assumes Swift 6.4; Mutex is in the Synchronization module since Swift 6.0 (SE-0433) and needs iOS 18, macOS 15 or later on Apple platforms.