skip to content

In Swift, when does a struct, enum or class conform to Sendable, and what must a final class satisfy to declare it?

level: middleimportance: must knowfreq 70%

answer

  1. marker protocol, checked by the compiler
  2. value types: every stored part
  3. non-public types get it free
  4. final, let, Sendable properties
  5. generic types need a where clause

basics

~20 s

A struct or enum is Sendable when every stored property or associated value is; non-public ones usually conform implicitly. A class passes the check only if it is final, stores only Sendable let properties and inherits from nothing but NSObject.

solid answer

~40 s

`Sendable` is a marker protocol the compiler checks. A struct or enum qualifies when all its stored properties or associated values are `Sendable`, and a non-`public` one gets the conformance implicitly; a `public` non-frozen type must declare it, and a generic type needs `extension Page: Sendable where Item: Sendable {}` because Swift infers no conditional conformance. A class can declare a checked conformance only when it is `final`, every stored property is a `let` of a `Sendable` type, it inherits from nothing except `NSObject`, and the conformance sits in the class's own source file. Actors and `@MainActor` classes are `Sendable` because their isolation protects their state. In Swift 6 language mode a failed check is an error; in Swift 5 mode it is a warning.

code

swift · 32 lines
swift
// Swift 6 language mode: every declaration here compiles.
struct Endpoint {                     // internal: implicitly Sendable
    let path: String
    var retries: Int
}

enum FetchResult: Sendable {          // checked: every payload is Sendable
    case ok([UInt8])
    case failed(code: Int)
}

final class APIConfig: Sendable {     // checked: final, only immutable lets
    let baseURL: String
    let timeout: Double
    init(baseURL: String, timeout: Double) {
        self.baseURL = baseURL
        self.timeout = timeout
    }
}

struct Page<Item> {                   // generic: no implicit conformance
    var items: [Item]
}
extension Page: Sendable where Item: Sendable {}

func send<T: Sendable>(_ value: T) {}

func demo() {
    send(Endpoint(path: "/feed", retries: 2))
    send(Page(items: [FetchResult.failed(code: 503)]))
    send(APIConfig(baseURL: "https://api.local", timeout: 30))
}

go deeper

for a junior

Recall that Sendable marks a type as safe to pass between tasks and actors, and that simple structs of Int and String already qualify.

for a middle

Explain the rules: value types by their stored parts, implicit conformance for non-public types, the four conditions for a checked final class, and the where clause for generics.

for a senior

Show you can read each diagnostic and pick the fix that keeps checking on: a let, a Mutex in a let, an actor or main-actor isolation, before reaching for @unchecked.

for a principal

Treat explicit Sendable on public types as API: decide which library types promise it, since adding a conformance later is easy and removing one breaks clients.

## What `Sendable` promises `Sendable` is a **marker protocol**: it has no methods to implement, only semantic requirements that the compiler checks. A value whose type is `Sendable` may cross from one **concurrency domain** to another (from a task to an actor, from the main actor into a `Task`, back out as a task's result) without two domains ever touching the same mutable state at once. The Swift book lists three ways for a type to be sendable: - it is a value type whose mutable state is made of other sendable data; - it has no mutable state, and its immutable state is sendable; - it has code that protects its mutable state, such as a `@MainActor` class or a class that serializes access itself. The first two the compiler can prove. The third it can prove only for isolation it understands (actors, global actors); for a hand-written lock it has to take your word, which is what `@unchecked Sendable` is for. ## Structs and enums: checked, and often implicit - A **struct** is `Sendable` when every stored property is `Sendable`; an **enum** when every associated value is. A `var` inside a struct is fine: each copy owns its own storage, so nothing is shared. - **Implicit conformance.** A struct or enum that is not `public` (and not `@usableFromInline`) conforms automatically when the check passes. An internal `struct Endpoint { let path: String; var retries: Int }` can be passed to a `T: Sendable` parameter with no annotation. - **Public types must opt in.** A `public` non-frozen struct or enum gets no implicit conformance, because it would silently become part of the module's API contract and a later non-`Sendable` stored property would break clients. Declare `: Sendable` on purpose. (A `@frozen` public type, whose layout is already promised, does conform implicitly.) - **Generic types.** Swift never infers a conditional conformance. `struct Page<Item> { var items: [Item] }` is not `Sendable`, not even as `Page<Int>`; write `extension Page: Sendable where Item: Sendable {}`. A type whose parameter is already constrained, `struct Box<T: Sendable>`, conforms implicitly. - **Same file.** A checked conformance must be declared in the type's own source file; from another file the compiler says the conformance "must occur in the same source file" and suggests `@unchecked Sendable` instead. ## Classes: one narrow checked case A class instance is shared by reference, so the compiler accepts a plain `Sendable` conformance only when it can prove there is nothing mutable to share: 1. the class is **`final`**, so no subclass can add mutable state; 2. every stored property is a **`let`**; 3. every stored property's type is itself **`Sendable`**; 4. the class inherits from **no class other than `NSObject`**. What each violation looks like in Swift 6 language mode: | Declaration | Compiler result | |---|---| | `final class TokenStore: Sendable { var token = "" }` | error: stored property 'token' of 'Sendable'-conforming class 'TokenStore' is mutable | | `class BaseClient: Sendable { let name = "api" }` | error: non-final class 'BaseClient' cannot conform to the 'Sendable' protocol | | `struct Request: Sendable { let logger: Logger }` with `Logger` a plain class | error: stored property 'logger' of 'Sendable'-conforming struct 'Request' has non-Sendable type 'Logger' | | `final class APIConfig: Sendable { let baseURL: String }` | compiles | A class that does have mutable state can still be `Sendable` in other ways: isolate it to a global actor, make it an actor instead, or keep its state inside a lock type such as the Synchronization module's `Mutex` held in a `let`. ## Other things that are `Sendable` - **Actors** are always `Sendable`; how an actor protects its state is the subject of the actors lesson. - **Global-actor-isolated classes**, such as a `@MainActor` class, are `Sendable`, because every access to their state goes through that actor. - **`@Sendable` function types.** A closure whose type is `@Sendable` may be called concurrently, so it may capture only `Sendable` values, by value. Capturing a local `var` is rejected with "reference to captured var 'attempts' in concurrently-executing code"; listing it in a capture list copies the current value instead. - **Standard library value types** (`Int`, `String`, `Array` and `Dictionary` of `Sendable` elements, `Optional` of a `Sendable` wrapped type) conform conditionally or unconditionally. ## How the checks surface by language mode In **Swift 6 language mode** every failure above is an error. In **Swift 5 mode** an explicit conformance that fails the check reports the same message as a warning, suffixed "this is an error in the Swift 6 language mode", which makes these warnings a to-do list for migration. Implicit conformance works identically in both modes. If you need to say the opposite, that a type is deliberately *not* `Sendable`, Swift 6.4 adds `~Sendable` on the type declaration; older code writes an unavailable `Sendable` extension.

  • Why does an internal struct get Sendable for free while the same struct marked public does not?
    For a non-`public` type, the whole module is visible to the compiler, so inferring the conformance cannot surprise anyone. For a `public` non-frozen type, an inferred conformance would become a promise to clients, and adding a non-`Sendable` stored property later would break their code. Swift makes library authors state that promise explicitly; a `@frozen` public type, whose layout is already fixed, still conforms implicitly.
  • Your final class holds a `let cache: [String: Data]` and a `var lastFetch: Date`. How can it become Sendable without @unchecked?
    The `var` breaks the checked rules. Either make it a `let` and create a new instance when it changes, move both values into an immutable lock such as `let state = Mutex<State>(...)` from the Synchronization module, which is itself `Sendable`, or isolate the class to `@MainActor` or turn it into an actor. Each keeps the compiler's check intact instead of switching it off.
  • A generic struct `Page<Item>` stores `[Item]`. Why can't you pass `Page<Int>` where Sendable is required?
    Implicit conformance applies to a generic type only when its stored data is guaranteed `Sendable`, and Swift never infers a conditional conformance. `Page<Item>` with an unconstrained `Item` therefore has no conformance at all, for any `Item`. Add `extension Page: Sendable where Item: Sendable {}` in the same file, and `Page<Int>` conforms.

  • Any class with only let properties can conform to Sendable, final or not.
  • Public structs are implicitly Sendable when all their properties are.
  • A var stored property makes a struct non-Sendable.
  • Swift infers Page<Int> as Sendable because Int is Sendable.
  • Sendable has a method requirement that types must implement.
  • Sendable conformance can be added from any file in the module.

Assumes Swift 6.4; the conformance checks are errors in Swift 6 language mode and the same messages as warnings in Swift 5 mode.