Actors

suggest change

An actor is a reference type that protects its mutable state from data races. Swift 5.5 added actors together with async and await.

An actor looks like a class, but only one piece of code at a time can touch its state. Code inside the actor uses its properties normally. Code outside has to await every call, and the actor runs those calls one after another.

The examples were compiled with Swift 6.4 on Windows, in the Swift 6 language mode:

swiftc -swift-version 6 -parse-as-library main.swift

The problem: shared mutable state

Here many child tasks of a task group increment one counter, which is an ordinary class:

final class Counter {
    var value = 0
    func increment() { value += 1 }
}

@main
struct App {
    static func main() async {
        let counter = Counter()
        await withTaskGroup(of: Void.self) { group in
            for _ in 0..<100_000 {
                group.addTask { counter.increment() }
            }
        }
        print(counter.value)
    }
}

In the Swift 6 language mode this doesn't compile:

error: passing closure as a 'sending' parameter risks causing data races between main actor-isolated code and concurrent execution of the closure
note: closure captures 'counter' which is accessible to main actor-isolated code

With -swift-version 5 it compiles. But the child tasks run in parallel on several threads, and value += 1 is a read followed by a write, so increments get lost. Three runs printed:

99707
99163
99369

The result should be 100000. Classes are reference types (see Reference Semantics), so every task works on the same object. Before actors, you protected such state with a lock or a serial dispatch queue.

Declaring an actor

Replace class with actor, and add await where the counter is used from outside:

actor Counter {
    var value = 0
    func increment() { value += 1 }
}

@main
struct App {
    static func main() async {
        let counter = Counter()
        await withTaskGroup(of: Void.self) { group in
            for _ in 0..<100_000 {
                group.addTask { await counter.increment() }
            }
        }
        print(await counter.value)
    }
}

Output:

100000

increment() is an ordinary, synchronous method. Callers outside the actor still have to await it. If another task is already running code on the actor, the call waits its turn, and await marks that possible wait. The waiting task is suspended, so no thread is blocked.

Internally each actor has a queue of work called a mailbox, and an executor that runs one job from it at a time. You never manage it yourself.

Isolation: inside vs outside

An actor's stored properties and methods are actor-isolated. The rules:

A bank account shows these rules:

enum BankError: Error {
    case insufficientFunds(balance: Int, requested: Int)
}

actor BankAccount {
    let number: String
    private(set) var balance: Int
    private var history: [String] = []

    init(number: String, balance: Int) {
        self.number = number
        self.balance = balance
    }

    func deposit(_ amount: Int) {
        balance += amount
        log("deposit \(amount)")
    }

    func withdraw(_ amount: Int) throws(BankError) {
        guard amount <= balance else {
            throw .insufficientFunds(balance: balance, requested: amount)
        }
        balance -= amount
        log("withdraw \(amount)")
    }

    // synchronous helper: inside the actor, no await needed
    private func log(_ entry: String) {
        history.append(entry)
    }

    func statement() -> [String] { history }
}

@main
struct App {
    static func main() async {
        let account = BankAccount(number: "PL-001", balance: 100)
        print("account", account.number)   // let constant: no await

        await account.deposit(50)
        do {
            try await account.withdraw(30)
            try await account.withdraw(500)
        } catch {
            print("error:", error)
        }
        print("balance:", await account.balance)
        print("history:", await account.statement())
    }
}

Output:

account PL-001
error: insufficientFunds(balance: 120, requested: 500)
balance: 120
history: ["deposit 50", "withdraw 30"]

withdraw checks the balance and subtracts in one synchronous method. Nothing else can run on the actor in between, so two withdrawals can never both pass the check against the same balance. A throwing method is called with try await from outside.

The compiler enforces the rules. This function breaks all of them:

func useCounter(_ counter: Counter) async {
    counter.increment()
    print(counter.value)
    await counter.value += 1
}

func syncUse(_ counter: Counter) {
    let v = await counter.value
}

Errors:

error: actor-isolated instance method 'increment()' cannot be called from outside of the actor
error: actor-isolated property 'value' cannot be accessed from outside of the actor
error: actor-isolated property 'value' can not be mutated from a nonisolated context
note: consider declaring an isolated method on 'Counter' to perform the mutation
error: 'await' in a function that does not support concurrency

The first two are fixed by adding await. The third needs a method on the actor. The last one means a synchronous function can't wait for an actor. Make it async, or start a Task.

Calling another actor

Inside an actor, only self is isolated. Another instance of the same actor type is a different actor, so calls to it need await:

enum BankError: Error {
    case insufficientFunds(balance: Int, requested: Int)
}

actor BankAccount {
    let number: String
    private(set) var balance: Int

    init(number: String, balance: Int) {
        self.number = number
        self.balance = balance
    }

    func deposit(_ amount: Int) { balance += amount }

    func withdraw(_ amount: Int) throws(BankError) {
        guard amount <= balance else {
            throw .insufficientFunds(balance: balance, requested: amount)
        }
        balance -= amount
    }

    func transfer(_ amount: Int, to other: BankAccount) async throws(BankError) {
        try withdraw(amount)          // self: synchronous, no await
        await other.deposit(amount)   // another actor: await
    }
}

// an `isolated` parameter runs the whole function on that actor
func applyInterest(to account: isolated BankAccount, percent: Int) {
    let interest = account.balance * percent / 100
    account.deposit(interest)        // no await: we're already isolated to `account`
    print("\(account.number): +\(interest) interest")
}

@main
struct App {
    static func main() async throws {
        let a = BankAccount(number: "A", balance: 100)
        let b = BankAccount(number: "B", balance: 0)

        try await a.transfer(40, to: b)
        await applyInterest(to: b, percent: 10)
        print("A:", await a.balance, "B:", await b.balance)
    }
}

Output:

B: +4 interest
A: 60 B: 44

transfer must be async because it awaits other. Each step runs on its own actor, but the transfer as a whole is not atomic. Between the withdrawal and the deposit, other code can see money that is in neither account.

A parameter marked isolated makes a free function run on the actor passed in. Inside it, the actor's state can be used synchronously, as if the function were a method. Callers await it like any actor method.

nonisolated members

Mark a method or computed property nonisolated when it doesn't touch the actor's mutable state. It can then be called synchronously, without await. This matters most for protocol conformances. Requirements like description, == and hash(into:) are synchronous, so an isolated method can't satisfy them:

import Foundation

actor User {
    let id: UUID
    let name: String
    var loginCount = 0

    init(name: String) {
        self.id = UUID()
        self.name = name
    }

    func login() { loginCount += 1 }

    // only uses `let` properties, so it can be called synchronously
    nonisolated var displayName: String { "@\(name.lowercased())" }

    nonisolated func greeting() -> String {
        "Hello, \(name)"
    }
}

// protocol requirements are synchronous: implement them as nonisolated
extension User: CustomStringConvertible {
    nonisolated var description: String { "User(\(name))" }
}

extension User: Hashable {
    nonisolated static func == (a: User, b: User) -> Bool { a.id == b.id }
    nonisolated func hash(into hasher: inout Hasher) { hasher.combine(id) }
}

@main
struct App {
    static func main() async {
        let ann = User(name: "Ann")
        print(ann.displayName, ann.greeting(), ann)   // no await
        await ann.login()

        let set: Set<User> = [ann, ann, User(name: "Bob")]
        print("unique users:", set.count)
    }
}

Output:

@ann Hello, Ann User(Ann)
unique users: 2

A nonisolated member is outside the actor, so it can't read mutable state:

actor User {
    var loginCount = 0
    nonisolated func report() -> String {
        "logins: \(loginCount)"
    }
}
error: actor-isolated property 'loginCount' can not be referenced from a nonisolated context

Protocols with async requirements are easier. A normal isolated method satisfies them, because callers from outside await anyway:

protocol Logger {
    func log(_ message: String) async
}

actor MemoryLogger: Logger {
    private var lines: [String] = []
    func log(_ message: String) {           // isolated method satisfies an async requirement
        lines.append(message)
    }
    func dump() -> [String] { lines }
}

actor IDGenerator {
    static let shared = IDGenerator()       // a thread-safe singleton
    private var next = 1
    private init() {}

    func make(prefix: String) -> String {
        defer { next += 1 }
        return "\(prefix)-\(next)"
    }
}

func work(_ logger: any Logger) async {
    let id = await IDGenerator.shared.make(prefix: "job")
    await logger.log("finished \(id)")
}

@main
struct App {
    static func main() async {
        let logger = MemoryLogger()
        await withTaskGroup(of: Void.self) { group in
            for _ in 1...4 {
                group.addTask { await work(logger) }
            }
        }
        for line in await logger.dump().sorted() { print(line) }
    }
}

Output:

finished job-1
finished job-2
finished job-3
finished job-4

IDGenerator.shared is the Singleton pattern made safe for concurrency. A class singleton with a mutable next would need a lock. The actor version gets the locking for free. In Swift 6, static let shared of an actor type is accepted because actors are Sendable.

Actor reentrancy

An actor runs one job at a time. But a method that hits an await gives up the actor while it is suspended, and other calls can then run on the actor. When the method resumes, the actor's state may have changed. This is called reentrancy. Swift chose it to avoid deadlocks, but it is the most common bug in actor code.

This wallet checks the balance, waits for an approval and then subtracts:

func approve(_ amount: Int) async -> Bool {
    try? await Task.sleep(for: .milliseconds(100))   // e.g. a call to a fraud-check service
    return true
}

actor Wallet {
    var balance = 100

    func withdraw(_ amount: Int, by who: String) async -> Bool {
        guard balance >= amount else {
            print("\(who): declined, balance \(balance)")
            return false
        }
        print("\(who): balance \(balance) is enough, asking for approval")
        let ok = await approve(amount)    // suspension point: other calls run here
        guard ok else { return false }
        balance -= amount
        print("\(who): withdrew \(amount), balance \(balance)")
        return true
    }
}

@main
struct App {
    static func main() async {
        let wallet = Wallet()
        async let first = wallet.withdraw(80, by: "first")
        async let second = wallet.withdraw(80, by: "second")
        _ = await (first, second)
        print("final balance:", await wallet.balance)
    }
}

Output (the order of first and second may vary):

first: balance 100 is enough, asking for approval
second: balance 100 is enough, asking for approval
second: withdrew 80, balance 20
first: withdrew 80, balance -60
final balance: -60

There is no data race here: every access to balance happened on the actor. The bug is in the logic. The check made before await was no longer true after it.

Fixes:

Here the money is reserved first:

actor Wallet {
    var balance = 100

    func withdraw(_ amount: Int, by who: String) async -> Bool {
        guard balance >= amount else {
            print("\(who): declined, balance \(balance)")
            return false
        }
        balance -= amount                 // reserve the money before suspending
        print("\(who): reserved \(amount), balance \(balance)")
        if await approve(amount) {
            return true
        }
        balance += amount                 // not approved: give it back
        return false
    }
}

With the same main (printing the results), the output is:

first: reserved 80, balance 20
second: declined, balance 20
(true, false)
final balance: 20

Reentrancy in a cache

The same problem shows up in caches. If a value is missing, the cache starts a download, and while that download is suspended, more requests for the same key arrive. None of them sees a cached value, so each one starts its own download. The fix is to cache the in-flight Task and have later callers await it:

func download(_ url: String) async throws -> String {
    print("downloading \(url)")
    try await Task.sleep(for: .milliseconds(200))
    return "<contents of \(url)>"
}

actor NaiveCache {
    private var cache: [String: String] = [:]

    func get(_ url: String) async throws -> String {
        if let cached = cache[url] { return cached }
        let data = try await download(url)   // other get() calls run while we wait
        cache[url] = data
        return data
    }
}

actor Cache {
    private enum Entry {
        case inProgress(Task<String, any Error>)
        case ready(String)
    }
    private var cache: [String: Entry] = [:]

    func get(_ url: String) async throws -> String {
        switch cache[url] {
        case .ready(let data):
            return data
        case .inProgress(let task):
            return try await task.value      // join the download already running
        case nil:
            break
        }
        let task = Task { try await download(url) }
        cache[url] = .inProgress(task)       // recorded before the first await
        do {
            let data = try await task.value
            cache[url] = .ready(data)
            return data
        } catch {
            cache[url] = nil                 // allow a retry after a failure
            throw error
        }
    }
}

@main
struct App {
    static func main() async throws {
        let naive = NaiveCache()
        print("naive:")
        async let a = naive.get("https://example.com")
        async let b = naive.get("https://example.com")
        async let c = naive.get("https://example.com")
        _ = try await (a, b, c)

        let cache = Cache()
        print("deduplicated:")
        async let d = cache.get("https://example.com")
        async let e = cache.get("https://example.com")
        async let f = cache.get("https://example.com")
        let results = try await [d, e, f]
        print(results.count, "results,", Set(results).count, "unique")
    }
}

Output:

naive:
downloading https://example.com
downloading https://example.com
downloading https://example.com
deduplicated:
downloading https://example.com
3 results, 1 unique

The key line is cache[url] = .inProgress(task). It runs before the first await, so every later call sees the entry. Unstructured Task {} and task.value are covered in more detail in Tasks and cancellation.

Global actors

An actor instance protects its own properties. A global actor is a single, program-wide actor whose isolation you can attach to anything: classes, functions, properties and global variables. Code marked with the same global actor runs on the same serial executor, so it can call each other's members synchronously.

Declare one with @globalActor and a static let shared instance:

@globalActor
actor StorageActor {
    static let shared = StorageActor()
}

// a global variable protected by the global actor
@StorageActor var totalWrites = 0

@StorageActor
final class Store {
    private var items: [String] = []

    func add(_ item: String) {
        items.append(item)
        totalWrites += 1   // same global actor: synchronous access
    }
    var count: Int { items.count }
}

@StorageActor
func addDefaults(to store: Store) {
    store.add("a")         // same global actor: no await
    store.add("b")
}

@main
struct App {
    static func main() async {
        let store = Store()
        await addDefaults(to: store)
        await store.add("c")
        print("items:", await store.count, "writes:", await totalWrites)
    }
}

Output:

items: 3 writes: 3

Store is a class, but marking it @StorageActor gives it the same protection as an actor. Unlike an actor, it can still inherit from a non-isolated base class. Global actors are useful when several types must share one lock, for example all the code that talks to a database.

Global variables in Swift 6

Global actors are also a fix for an error you'll meet often in Swift 6. Any mutable global or static variable is shared state:

var requestCount = 0

final class Settings {
    static var shared = Settings()
    var theme = "light"
}
error: var 'requestCount' is not concurrency-safe because it is nonisolated global shared mutable state
note: convert 'requestCount' to a 'let' constant to make 'Sendable' shared state immutable
note: add '@MainActor' to make var 'requestCount' part of global actor 'MainActor'
note: disable concurrency-safety checks if accesses are protected by an external synchronization mechanism
error: static property 'shared' is not concurrency-safe because it is nonisolated global shared mutable state

The fixes are the ones the notes list. Make it a let. Isolate it to a global actor (@MainActor or your own, like totalWrites above). Turn the type into an actor. Or, as a last resort, use nonisolated(unsafe). Sendable and Swift 6 data-race safety covers these options.

@MainActor

MainActor is a global actor provided by the standard library. Its executor is the program's main thread. On Apple platforms, UIKit, AppKit and SwiftUI views are @MainActor, so UI updates must happen there. A typical "view model" is isolated to the main actor and awaits slow work elsewhere.

The next program uses the #isolation macro to print the actor the code runs on:

func whereAmI(isolation: isolated (any Actor)? = #isolation) -> String {
    if let isolation { return "\(type(of: isolation))" }
    return "no actor (thread pool)"
}

@MainActor
final class ViewModel {
    var status = "idle"
    var items: [String] = []

    func refresh() async {
        status = "loading"
        print("refresh runs on:", whereAmI())
        let loaded = await fetchItems()          // runs off the main actor
        items = loaded                           // back on the main actor
        status = "loaded \(items.count) items"
    }
}

// a nonisolated async function runs on the shared thread pool
func fetchItems() async -> [String] {
    print("fetchItems runs on:", whereAmI())
    try? await Task.sleep(for: .milliseconds(100))
    return ["a", "b", "c"]
}

func backgroundWork() async {
    let result = (1...1000).reduce(0, +)
    await MainActor.run {
        print("MainActor.run closure runs on:", whereAmI(), "result:", result)
    }
}

@main
struct App {
    static func main() async {
        print("main runs on:", whereAmI())
        let vm = ViewModel()
        await vm.refresh()
        print(vm.status)            // no await: main() is on the main actor too
        await backgroundWork()
    }
}

Output:

main runs on: MainActor
refresh runs on: MainActor
fetchItems runs on: no actor (thread pool)
loaded 3 items
MainActor.run closure runs on: MainActor result: 500500

Points to notice:

On Apple platforms the same pattern updates the UI. This code isn't run here, because UIKit isn't available on Windows:

@MainActor
final class ProfileViewController: UIViewController {
    let nameLabel = UILabel()

    func load(userID: Int) {
        Task {                                   // inherits @MainActor
            let user = try await api.fetchUser(id: userID)   // network call off the main thread
            nameLabel.text = user.name           // back on the main actor
        }
    }
}

Swift 6.2 added an opt-in mode in which code is @MainActor by default, and nonisolated async functions run on the caller's actor unless they are marked @concurrent. Sendable and Swift 6 data-race safety covers these settings.

Actors compared with classes

Actors share a lot with classes:

They differ in these ways:

When to use what:

Need Use
Immutable data, or data copied between tasks struct / enum (value types, Sendable when their contents are)
Mutable state shared by concurrent tasks, used from async code actor
State that must stay with the UI a @MainActor class
Several types that must share one serial executor a custom @globalActor
Mutable state that synchronous code must access quickly, without await Mutex from the Synchronization module, or a lock

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents