Actors

The interviewer asks

“What are actors in Swift? When would you use them?”

How to answer

An actor is a reference type that protects its mutable state by serializing access: only one task runs on a given actor at a time, and code outside the actor must await to call it. That makes data races on its state impossible, and in Swift 6 language mode the compiler enforces it. I use an actor for shared mutable state that's accessed from several tasks (a cache, a token store, a download coordinator), @MainActor for UI state, and a Mutex when I need short synchronous critical sections without await.

Key points

  • actor Store { var state }: inside, access is synchronous; outside, every call and property read is await (and you can't set its properties from outside)
  • Actors are Sendable by construction; what you pass in and out must be Sendable or sending
  • Actors are reentrant: while a method is suspended at an await, other calls can run on the actor, so state can change across an await (see Actor Reentrancy). This also means two actors awaiting each other don't deadlock
  • Each await into an actor is a potential hop between executors; group related work in one actor method rather than many small calls
  • nonisolated members and immutable lets skip isolation; an isolated parameter runs a whole function on an actor (see Actor Isolation Rules)
  • Custom executors: an actor can run on a specific SerialExecutor (e.g. a DispatchSerialQueue) by overriding unownedExecutor, mainly for interop with code that already owns a queue
  • isolated deinit (Swift 6.2) lets a deinit call isolated methods, on actors and on @MainActor classes

If they dig deeper

Actor vs Mutex (async serialized access vs synchronous, non-suspending sections; see NSLock and Mutex). Actor vs serial DispatchQueue (compile-time checking, no blocking sync, priority escalation). Why actors don't guarantee FIFO ordering of calls. Global actors for isolation shared across many types (see Global Actors). Actor.assumeIsolated / preconditionIsolated when you know you're on the actor's executor. Actors don't support inheritance.

Common pitfalls

Check-then-act across an await (two callers both miss the cache and both download). Expecting actor methods to run in call order. Making an actor for state that only the main actor touches (just use @MainActor). Many tiny await actor.property reads instead of one method that returns a snapshot. Doing heavy CPU work inside an actor method and blocking every other caller. Assuming actors run "in the background": they run wherever their executor runs.

How to use it

swift
actor ProfileStore {
    private var cache: [Int: Profile] = [:]
    private(set) var hits = 0

    func profile(_ id: Int) async throws -> Profile {
        if let cached = cache[id] { hits += 1; return cached }
        let fresh = try await fetchProfile(id)       // suspends: other calls may run here
        cache[id] = fresh                            // re-entered callers may have written too
        return fresh
    }

    func clear() { cache.removeAll() }               // synchronous inside the actor
}

@MainActor
func showProfile(store: ProfileStore) async throws {
    let p = try await store.profile(42)             // hop to the actor and back
    let hits = await store.hits                     // reading state from outside: await
    print(p.id, hits)
}

// Custom executor: run the actor on a queue a C library already uses
actor SQLiteConnection {
    private let queue = DispatchSerialQueue(label: "db")
    nonisolated var unownedExecutor: UnownedSerialExecutor { queue.asUnownedSerialExecutor() }
}

actor Recorder {
    private var buffer: [String] = []
    func flush() { buffer.removeAll() }
    isolated deinit { flush() }                      // calls an isolated method
}

Best practices

  • Use an actor for shared mutable state touched by several tasks; @MainActor for UI; Mutex for tiny synchronous sections
  • Re-check state after every await inside an actor method, or deduplicate in-flight work
  • Batch work into one actor method instead of many cross-actor property reads
  • Keep actor methods short; move CPU-heavy work to a @concurrent function
  • Reach for custom executors only for interop, not as a performance tweak

Related concepts

  • Actor isolation rules, actor reentrancy, MainActor, global actors, Sendable, Mutex, nonisolated