skip to content

In Swift, what does declaring a ResponseCache class `@unchecked Sendable` actually change, and when is that a safe choice?

level: seniorimportance: should knowfreq 55%

answer

  1. a promise the compiler cannot verify
  2. no lock, no runtime check
  3. every access behind one lock
  4. Mutex in a let keeps checking
  5. ~Sendable for the opposite promise

basics

~20 s

@unchecked Sendable only switches off the compiler's Sendable checks for that type; it adds no lock and no run-time check. It is safe only when the type itself guards every access to its mutable state, for example with a lock or Mutex.

solid answer

~40 s

`@unchecked Sendable` tells the compiler to stop checking the type's stored properties and to trust that instances are safe to share. It adds no synchronization, so if `ResponseCache` keeps an unguarded `var entries` dictionary, two tasks calling `store` race, and nothing in the language catches it; Thread Sanitizer might. It is defensible when every read and write of mutable state goes through one lock and no reference to that state escapes, or when the state is immutable in a way the checker cannot see, such as a non-final class. Prefer a form the compiler can verify: a `final` class whose only state is `let entries = Mutex<...>(...)` from the Synchronization module (iOS 18 and macOS 15 or later) is checked `Sendable`. In Swift 6.4, `~Sendable` declares the opposite, a type deliberately not `Sendable`.

code

swift · 26 lines
swift
import Synchronization

// Compiles, but nothing guards `entries`: two tasks calling store race.
final class UncheckedCache: @unchecked Sendable {
    private var entries: [String: [UInt8]] = [:]
    func store(_ bytes: [UInt8], for key: String) { entries[key] = bytes }
}

// Checked Sendable: final, and its only stored property is an immutable Mutex.
final class ResponseCache: Sendable {
    private let entries = Mutex<[String: [UInt8]]>([:])

    func store(_ bytes: [UInt8], for key: String) {
        entries.withLock { $0[key] = bytes }
    }

    func bytes(for key: String) -> [UInt8]? {
        entries.withLock { $0[key] }
    }
}

func prefetch(into cache: ResponseCache, keys: [String]) {
    for key in keys {
        Task { cache.store([1, 2, 3], for: key) }
    }
}

go deeper

for a junior

Remember that @unchecked Sendable silences the compiler; it does not make a class thread-safe.

for a middle

Explain which checks @unchecked removes, and show a Mutex-based or let-only class that stays checked instead.

for a senior

Review an @unchecked type like a lock-based design: every read and write guarded, nothing escaping, final class, small surface, and know when ~Sendable is the better statement.

for a principal

Decide how unchecked conformances are approved and tracked, so they stay rare, small and documented instead of a migration shortcut.

## What `@unchecked` switches off A plain `Sendable` conformance on a class is checked: the class must be `final`, its stored properties must be `let`, and their types must be `Sendable`. Writing `@unchecked Sendable` keeps the conformance and **drops the checks**. The compiler now accepts the type anywhere a `Sendable` value is required (captured by a `Task`, passed to an actor, stored in a global constant) and never looks inside it again. What it does **not** do matters more: - it adds **no lock**, no queue and no actor hop; - it adds **no run-time check**: a race on an `@unchecked Sendable` type is ordinary undefined behaviour, found, if at all, by a tool such as Thread Sanitizer or by a crash report; - it is **inherited**: a subclass is `Sendable` too, and the compiler only warns that the class "must restate inherited '@unchecked Sendable' conformance", even in Swift 6 language mode, while it happily adds a new unguarded `var`. So the annotation is a promise, and the reviewer, not the compiler, now has to verify it. ## The failure mode ```swift final class ResponseCache: @unchecked Sendable { private var entries: [String: [UInt8]] = [:] func store(_ bytes: [UInt8], for key: String) { entries[key] = bytes } } ``` This compiles in Swift 6 mode, the migration errors disappear, and the first time two prefetch tasks call `store` at once they mutate the same dictionary concurrently. That is the classic way a team "finishes" a Swift 6 migration with the same races it started with, now silenced. ## When it is a reasonable choice `@unchecked Sendable` is legitimate when the type really does protect itself and the compiler cannot see it: 1. **Every** access to mutable state, reads included, goes through one lock (`NSLock`, `os_unfair_lock`, a serial `DispatchQueue`), and no reference to the protected storage escapes the critical section. 2. The state is effectively immutable but the class cannot satisfy the checker, for instance a non-final class with only `let` properties, or a type wrapping a C handle that is documented as thread-safe. 3. A wrapper around an older API whose thread-safety is documented but not annotated. Even then, keep the unchecked part small: put the lock and the state in one tiny type, mark that `@unchecked`, and let everything built from it be checked normally. ## Alternatives the compiler can verify | Approach | What the compiler checks | Cost | |---|---|---| | `final class` with only `let` properties of `Sendable` types | everything | state must be immutable | | `final class` whose state is `let entries = Mutex<[String: [UInt8]]>([:])` | everything outside the `Mutex` | each access is a short `withLock` call; needs iOS 18 or macOS 15 | | an actor (covered in the lesson on actors) | isolation of every access | callers must `await` | | `@MainActor` isolation | every access runs on the main actor | work runs on the main thread | | keep it non-`Sendable` and hand instances over with `sending` | region analysis | one owner at a time | `Mutex` is worth knowing by name. It lives in the Synchronization module, is itself declared `@unchecked Sendable` once, in the Synchronization module's own source, and is non-copyable, and the compiler requires it to be stored in a `let`. A class whose only stored property is that `let` passes the ordinary checked rules: the audited `@unchecked` lives in one place everyone trusts. For a single variable rather than a type, `nonisolated(unsafe)` is the equivalent opt-out for a global, a static property or a local copy; it carries the same risk. ## The opposite promise: `~Sendable` (Swift 6.4) Library authors also need to say "deliberately *not* `Sendable`". The old spelling was an unavailable extension, `@available(*, unavailable) extension Transport: Sendable {}`, but that unavailability is inherited: a thread-safe subclass that declares `@unchecked Sendable` gets "warning: 'PinnedLegacy' inherits an unavailable 'Sendable' conformance; conforming here risks data races". Swift 6.4's `~Sendable` (SE-0518), written on the type declaration itself, suppresses the conformance and inferred sendability for that type only, so a subclass may still declare `@unchecked Sendable`. Pair it with the `ExplicitSendable` warning group (`-Wwarning ExplicitSendable`, off by default) to audit which public types still say nothing. ## Reviewing an `@unchecked` in a pull request - Ask what protects each mutable property, and check that reads take the lock too. - Check the class is `final`, or that every subclass restates the promise and keeps it. - Look for methods that return a reference to internal mutable state. - Prefer replacing it with `Mutex`, an actor or a `let` before approving it.

  • Why is a final class holding `let state = Mutex<State>(...)` checked Sendable, when Mutex itself is @unchecked?
    The class meets the ordinary rules: it is `final`, and its only stored property is a `let` whose type, `Mutex`, conforms to `Sendable`. The unchecked promise is made once, inside the standard library, by a type whose whole purpose is to guard its value, so your own type needs no `@unchecked` of its own.
  • A subclass of an @unchecked Sendable base class adds a `var retryCount`. What does the compiler say?
    Only a warning that the subclass must restate the inherited `@unchecked Sendable` conformance, even in Swift 6 language mode. The new `var` is not checked, because the inherited conformance is unchecked. That is why unchecked types should be `final`, or subclasses reviewed as carefully as the base.
  • When would you write `~Sendable` instead of leaving a public type without any Sendable conformance?
    When you have audited the type and decided it is deliberately not `Sendable`. `~Sendable` (Swift 6.4) records that decision, suppresses inferred conformance, satisfies the `ExplicitSendable` audit warnings, and, unlike an unavailable extension, still lets a subclass declare `@unchecked Sendable`.

  • @unchecked Sendable adds a lock around the class's properties.
  • The runtime traps if an @unchecked Sendable type is used concurrently.
  • If it compiles in Swift 6 mode, it cannot have a data race.
  • Guarding writes with a lock is enough; reads can skip it.
  • Subclasses of an @unchecked Sendable class are checked again.
  • An unavailable Sendable extension still lets a subclass opt back in cleanly.

Assumes Swift 6.4; Mutex ships with the Swift 6.0 standard library (iOS 18 and macOS 15 or later), and ~Sendable arrived in Swift 6.4 (SE-0518).