Pocket How
Swift and concurrency

Swift actors and Sendable explained: reentrancy, sending and Mutex

iOS 13+, Mutex on iOS 18+. Intermediate. By Cihat Salik, .

Short answer

An actor serializes access to its own mutable state, but every await inside it lets other callers in, so check and update state before suspending. Sendable marks values safe to share, and sending moves a non-Sendable value across a boundary once. Use a Mutex for small synchronous state and an actor only for shared state with async work.

What each tool is for

Swift 6 gives you several ways to make shared state safe, and they overlap enough to be confusing. Actors, global actors, Sendable, sending, Mutex and @unchecked Sendable each answer a slightly different question. Picking the wrong one rarely breaks correctness, but it can spread async through a codebase that did not need it, or hide a logical race behind code that compiles cleanly. This article walks through each one with the decision you are actually making.

Actors protect their own mutable state

An actor (SE-0306, Swift 5.5) is a reference type whose stored properties can only be touched from inside its isolation domain. The runtime runs one piece of the actor’s code at a time. Callers outside the actor await every call, because they may have to wait their turn.

import Foundation

actor NaiveCache {
    private var images: [URL: Data] = [:]

    func image(for url: URL) async throws -> Data {
        if let cached = images[url] {
            return cached
        }
        let (data, _) = try await URLSession.shared.data(from: url)
        images[url] = data
        return data
    }
}

This compiles in Swift 6 and has no data race. It does have a bug.

Reentrancy

While the actor waits at try await URLSession.shared.data(from:), it is free to run other calls. That is reentrancy, and it is deliberate: an actor that blocked during every await would deadlock easily. The cost is that state you read before an await may have changed after it.

In the cache above, ten views asking for the same URL at the same time all miss the cache, and all ten start a download. Matt Massicotte calls this a logical race in Stateful Systems: no memory is accessed concurrently, so the compiler is happy, but the outcome depends on timing. His rule is to check and update state synchronously, before the first suspension point.

For a cache, that means recording the in-flight work before you await it:

import Foundation

actor ImageCache {
    private var images: [URL: Data] = [:]
    private var inFlight: [URL: Task<Data, any Error>] = [:]

    func image(for url: URL) async throws -> Data {
        if let cached = images[url] {
            return cached
        }
        if let existing = inFlight[url] {
            return try await existing.value
        }
        let task = Task {
            let (data, _) = try await URLSession.shared.data(from: url)
            return data
        }
        inFlight[url] = task
        defer { inFlight[url] = nil }
        let data = try await task.value
        images[url] = data
        return data
    }
}

The check of inFlight and the insert happen with no await between them, so no other call can slip in. Every later caller finds the task and awaits the same download.

The same reasoning applies to any read-modify-write that spans an await:

actor Account {
    private(set) var balance = 0

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

    private func log(_ message: String) async {}
}

Update first, then suspend. If you read balance into a local, await, and write before + amount back, two concurrent deposits lose one of them.

Nonisolated members

Anything on an actor that does not touch mutable state can be marked nonisolated so callers do not need await. Immutable let properties of Sendable type are already accessible this way from inside the module.

import Foundation

actor Downloader {
    nonisolated let id = UUID()

    nonisolated func label() -> String {
        "Downloader \(id)"
    }
}

Global actors isolate many types to one domain

A global actor (SE-0316) is a single shared actor you can attach to types, functions and properties anywhere. @MainActor is the one you use daily. You can define your own:

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

@DatabaseActor
final class Database {
    private var rows: [String] = []

    func insert(_ row: String) {
        rows.append(row)
    }

    var count: Int {
        rows.count
    }
}

Every @DatabaseActor declaration shares one serial domain, so Database and any helper types annotated the same way can call each other synchronously. Custom global actors are rarely needed in apps. Reach for one when several types must share a serial context that is not the main thread, such as a database connection.

A global-actor-isolated class is implicitly Sendable. Massicotte’s problematic patterns list includes writing Sendable on such types anyway, because it suggests a misunderstanding.

Sendable marks values that can cross

Sendable (SE-0302) is a marker protocol: a promise that a value can be used from several isolation domains at once without a race. The compiler checks the promise.

  • Value types whose stored properties are all Sendable are Sendable. Inside a module this is inferred for non-public structs and enums. Public types need the conformance written out.
  • Final classes with only immutable Sendable stored properties can conform.
  • Actors and global-actor-isolated classes are Sendable automatically.
  • Closures marked @Sendable can only capture Sendable values.
import Foundation

struct UploadItem: Sendable {
    let id: UUID
    let fileURL: URL
}

final class Theme: Sendable {
    let accentName: String

    init(accentName: String) {
        self.accentName = accentName
    }
}

When a class guards its own state with a lock the compiler cannot see, @unchecked Sendable tells the compiler to trust you. Use it only with a real lock, and prefer Mutex when your deployment target allows.

Swift 6.4 adds SE-0518, ~Sendable, so a public type can state that it is non-Sendable on purpose. It also stops the compiler from inferring Sendable for that type, which matters for classes whose subclasses may add mutable state.

sending moves a value once

Many types are not Sendable and never will be, yet you still need to hand one to another task. Swift 6’s region-based isolation (SE-0414) lets the compiler prove that a non-Sendable value is no longer used by the sender. SE-0430 exposes that in function signatures with the sending keyword.

final class ExportJob {
    var items: [String] = []
}

func run(_ job: sending ExportJob) {
    Task {
        job.items.append("done")
    }
}

@MainActor
func startExport() {
    let job = ExportJob()
    job.items = ["a", "b"]
    run(job)
}

ExportJob is a plain mutable class. Passing it to run is allowed because startExport never touches job again. Add print(job.items) after the call and the compiler reports “sending ‘job’ risks causing data races”. The standard library uses sending in Task.init and the continuation APIs, which is why you can create a non-Sendable value and pass it into a task without errors.

The rule of thumb: Sendable is for values that are shared, sending is for values that are handed over.

Mutex for small synchronous state

The Synchronization framework’s Mutex (SE-0433, Swift 6.0) is a lock that owns the value it protects. It is available from iOS 18, and a type that stores its state in a Mutex can be checked Sendable without @unchecked.

import Synchronization

@available(iOS 18.0, macOS 15.0, *)
final class RequestCounter: Sendable {
    private let counts = Mutex<[String: Int]>([:])

    func record(_ endpoint: String) {
        counts.withLock { $0[endpoint, default: 0] += 1 }
    }

    func count(for endpoint: String) -> Int {
        counts.withLock { $0[endpoint, default: 0] }
    }
}

Callers use it synchronously, with no await. That is the main reason to choose it. Donny Wals makes this point in Protecting mutable state with Mutex in Swift: if you would need a lot of async code just to talk to an actor, a mutex is probably the better fit. He also notes that a mutex blocks while it waits, so keep the work inside withLock short.

Jacob Bartlett adds two practical cautions in The Synchronization Framework in Swift 6: keep the critical section small, and never call withLock recursively on the same mutex, which crashes on Apple platforms. withLockIfAvailable returns nil instead of waiting when you cannot afford to block.

You cannot await inside withLock. If the protected work is itself async, you need an actor.

When a class should be an actor

The community view is fairly consistent here. Donny Wals and Matt Massicotte both warn against turning types into actors by default, because every access becomes async and that spreads. Massicotte lists stateless actors as a problematic pattern: an actor with no mutable state has nothing to protect, and a nonisolated async function does the job.

Use this order:

  1. Does it hold mutable state at all? If not, make it a Sendable struct or a final class with let properties. No actor.
  2. Is it only used from UI code? Make it @MainActor. Most view models, coordinators and controllers belong here.
  3. Is the state small and accessed synchronously from many places? Use a Mutex inside a Sendable class, on iOS 18 and later.
  4. Is the state shared across isolation domains, and does the work involve await? That is an actor: caches with downloads, sync engines, connection pools.
  5. Do several types need to share one serial context off the main thread? A custom global actor.

A related trap: actors and protocols with synchronous requirements fit badly. Massicotte notes that an actor conforming to a protocol with synchronous methods often fails to compile or forces nonisolated workarounds. If the protocol is synchronous, the conforming type is probably not an actor.

Traps and edge cases

  • Actors are not queues. There is no ordering guarantee between separate callers. If order matters, put the ordering in the actor’s own state.
  • deinit is nonisolated by default. In a @MainActor class it cannot call the class’s main-actor methods. Swift 6.2 added isolated deinit (SE-0371) for classes that need it.
  • Locks inside actors. An actor already serializes access. Adding a lock around its state is redundant and risks deadlocks.
  • @unchecked Sendable spreads. Once a type is marked unchecked, nothing stops someone adding a mutable property later. Prefer a checked conformance with Mutex or immutable state.
  • Mutable var on a Sendable class. The compiler rejects it. If you need mutation, protect it with a mutex or move the class to an actor.

Quick reference

Need Use Minimum
Share an immutable value Sendable struct, enum or final class Swift 5.5
UI state @MainActor class Swift 5.5
Hand a non-Sendable value to another task once sending parameter Swift 6.0
Small state, synchronous access Mutex in a Sendable class Swift 6.0, iOS 18
Shared state with async work actor Swift 5.5
Serial context shared by several types Custom @globalActor Swift 5.5
Your own lock, already audited @unchecked Sendable Swift 5.5
Deliberately non-Sendable public type ~Sendable Swift 6.4

Sources and further reading

Read next