Sendable and Swift 6 data-race safety

suggest change

A data race happens when two threads access the same memory at the same time and at least one of them writes. The result is undefined: lost updates, corrupted data, or crashes that only show up sometimes. Most languages leave it to you to avoid them. In the Swift 6 language mode the compiler checks for them, and a possible data race is a compile-time error.

The pieces arrived over several releases:

Version What it added
Swift 5.5 Sendable protocol, @Sendable closures, actors, async/await
Swift 5.7 -strict-concurrency=minimal/targeted/complete to get checks as warnings
Swift 5.10 complete data-race checking (as warnings)
Swift 6.0 Swift 6 language mode makes the checks errors, sending, region-based isolation, nonisolated(unsafe)
Swift 6.2 "approachable concurrency": default MainActor isolation, nonisolated(nonsending), @concurrent

This article explains the rules and the typical errors with their fixes. It builds on async and await, Structured concurrency with async let and TaskGroup, Actors and Tasks and cancellation.

All examples were compiled with Swift 6.4.1:

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

Note that plain swiftc still defaults to the Swift 5 language mode. A SwiftPM package with // swift-tools-version: 6.0 or later uses Swift 6 mode by default.

A data race the compiler catches

Ten child tasks increment the same counter:

final class Counter {
    var value = 0
}

@main
struct App {
    static func main() async {
        let counter = Counter()
        await withTaskGroup(of: Void.self) { group in
            for _ in 0..<10 {
                group.addTask {
                    // 10 tasks write to the same memory at the same time
                    for _ in 0..<100_000 { counter.value += 1 }
                }
            }
        }
        print("expected 1000000, got", counter.value)
    }
}

In the Swift 5 language mode this compiles without a warning. It runs and prints a different wrong number each time:

expected 1000000, got 178001

In the Swift 6 mode it doesn't compile:

race.swift:11:23: error: passing closure as a 'sending' parameter risks causing data races
between main actor-isolated code and concurrent execution of the closure
11 |                 group.addTask {
13 |                     for _ in 0..<100_000 { counter.value += 1 }
   |                                            `- note: closure captures 'counter' which is accessible to main actor-isolated code

The compiler sees that counter is a class instance with mutable state, that main can reach it, and that the child tasks run concurrently with main and with each other. It doesn't need to prove a race happens, only that one could.

The checks are based on isolation domains. Each actor (including @MainActor) is one domain. Code that isn't isolated to any actor (nonisolated) runs on the shared thread pool. A value may cross from one domain to another only if that is safe: either its type is Sendable, or the compiler can prove that nothing else still uses it.

The Sendable protocol

Sendable is a marker protocol with no requirements. It says "values of this type can be shared between concurrent code safely". The compiler checks that the claim is true:

// Value types whose stored properties are all Sendable
struct Point: Sendable {
    var x: Double
    var y: Double
}

enum Shape: Sendable {
    case circle(center: Point, radius: Double)
    case polygon([Point])
}

// A final class with only immutable Sendable properties
final class User: Sendable {
    let id: Int
    let name: String
    init(id: Int, name: String) { self.id = id; self.name = name }
}

// A class with mutable state can't be Sendable
final class Account: Sendable {
    var balance = 0
}

// A non-final class can't be Sendable either
class Base: Sendable {
    let id = 1
}

// A struct with a non-Sendable property
class Logger {}
struct Request: Sendable {
    let url: String
    let logger: Logger
}

The last three types are rejected:

rules.swift:21:9: error: stored property 'balance' of 'Sendable'-conforming class 'Account' is mutable
rules.swift:25:7: error: non-final class 'Base' cannot conform to the 'Sendable' protocol
rules.swift:33:9: error: stored property 'logger' of 'Sendable'-conforming struct 'Request' has non-Sendable type 'Logger'

The rules:

Inferred conformance

You don't have to write : Sendable on every struct. For non-public structs and enums the compiler infers it:

func requireSendable<T: Sendable>(_ value: T) {
    print("\(T.self) is Sendable")
}

struct Size {          // no ': Sendable' written
    var width: Int
    var height: Int
}

enum Direction { case up, down }

@main
struct App {
    static func main() {
        requireSendable(42)
        requireSendable("text")
        requireSendable([1, 2, 3])
        requireSendable(["a": [1.5]])
        requireSendable(Size(width: 2, height: 3))
        requireSendable(Direction.up)
        requireSendable((1, "tuple"))
    }
}

Output:

Int is Sendable
String is Sendable
Array<Int> is Sendable
Dictionary<String, Array<Double>> is Sendable
Size is Sendable
Direction is Sendable
(Int, String) is Sendable

Inference doesn't happen for public types (a library shouldn't promise Sendable by accident, since removing it later breaks clients) and never for classes. Passing a public struct Token or a final class Box without an explicit conformance gives error: type 'Token' does not conform to the 'Sendable' protocol.

For a generic type, use a conditional conformance:

public struct Pair<A, B> {
    public var first: A
    public var second: B
}
// Sendable only when both element types are
extension Pair: Sendable where A: Sendable, B: Sendable {}

Pair<Int, String> is now Sendable, and Pair<Int, Logger> is not.

Fixing shared mutable state

Back to the counter. There are four common fixes:

import Foundation
import Synchronization

// Fix 1: an actor serializes access to its state
actor ActorCounter {
    var value = 0
    func increment() { value += 1 }
}

// Fix 2: a Mutex makes the class Sendable, checked by the compiler
final class MutexCounter: Sendable {
    private let state = Mutex(0)
    func increment() { state.withLock { $0 += 1 } }
    var value: Int { state.withLock { $0 } }
}

// Fix 3: you promise thread safety yourself
final class LockedCounter: @unchecked Sendable {
    private let lock = NSLock()
    private var _value = 0 // protected by lock
    func increment() { lock.withLock { _value += 1 } }
    var value: Int { lock.withLock { _value } }
}

@main
struct App {
    static func main() async {
        let a = ActorCounter()
        let m = MutexCounter()
        let l = LockedCounter()
        await withTaskGroup(of: Void.self) { group in
            for _ in 0..<10 {
                group.addTask {
                    for _ in 0..<10_000 {
                        await a.increment()
                        m.increment()
                        l.increment()
                    }
                }
            }
        }
        print("actor:", await a.value)
        print("mutex:", m.value)
        print("lock: ", l.value)

        // Fix 4: don't share at all, return values and combine them
        let total = await withTaskGroup(of: Int.self) { group in
            for _ in 0..<10 {
                group.addTask {
                    var local = 0
                    for _ in 0..<10_000 { local += 1 }
                    return local
                }
            }
            var sum = 0
            for await part in group { sum += part }
            return sum
        }
        print("sum:  ", total)
    }
}

Output:

actor: 100000
mutex: 100000
lock:  100000
sum:   100000

@Sendable closures

A closure can capture variables, so a closure that runs concurrently can race on what it captured. A function type marked @Sendable promises that the closure is safe to call from any domain. The compiler checks what such a closure captures:

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

func runLater(_ work: @escaping @Sendable () -> Void) {
    work()
}

func demo() {
    var count = 0
    runLater { count += 1 }            // captures a var

    let cache = Cache()
    runLater { print(cache.items) }     // captures a non-Sendable class

    let plain: () -> Void = { print("hi") }
    runLater(plain)                     // non-Sendable function value
}

All three calls are errors:

closures_err.swift:9:16: error: mutation of captured var 'count' in concurrently-executing code
closures_err.swift:12:22: error: capture of 'cache' with non-Sendable type 'Cache' in a '@Sendable' closure
closures_err.swift:15:14: error: converting non-Sendable function value to '@Sendable () -> Void' may introduce data races

A @Sendable closure may capture let constants of Sendable types, and copies of variables through a capture list. You need @Sendable whenever a closure is stored in a Sendable type or handed to code that may run it on another thread:

// A Sendable struct can store only @Sendable closures
struct Job: Sendable {
    let name: String
    let run: @Sendable (Int) async -> Int
}

func makeJobs() -> [Job] {
    let factor = 10          // let of a Sendable type: fine to capture
    var offset = 1
    offset += 1
    return [
        Job(name: "scale") { $0 * factor },
        // capture a copy of the var with a capture list
        Job(name: "shift") { [offset] in $0 + offset },
    ]
}

@main
struct App {
    static func main() async {
        let jobs = makeJobs()
        let results = await withTaskGroup(of: (String, Int).self) { group in
            for job in jobs {
                group.addTask { (job.name, await job.run(5)) }
            }
            var r: [String: Int] = [:]
            for await (name, value) in group { r[name] = value }
            return r
        }
        for (name, value) in results.sorted(by: { $0.key < $1.key }) {
            print(name, value)
        }
    }
}

Output:

scale 50
shift 7

The completion handlers in the async and await article are typed @escaping @Sendable (Result<Int, FetchError>) -> Void for the same reason: they are called later from another thread.

sending and region-based isolation

If every value crossing a domain had to be Sendable, you couldn't create an ordinary class instance and hand it to an actor. Swift 6 is smarter. It tracks regions of values that may refer to each other. A non-Sendable value can move to another domain if nothing in the current domain uses it afterwards:

final class Report {          // not Sendable
    var lines: [String] = []
}

actor Archive {
    var reports: [Report] = []
    func store(_ report: Report) {
        reports.append(report)
        print("archived report with \(report.lines.count) lines")
    }
}

func build() async {
    let archive = Archive()

    let report = Report()
    report.lines.append("total: 42")
    // OK: 'report' is not used after this point, so it can move
    // into the actor's isolation domain
    await archive.store(report)

    let other = Report()
    await archive.store(other)
    other.lines.append("oops")  // used after it was sent
}

The first transfer is accepted. The second one is rejected, because after other was given to the actor, build touches it again while the actor may be using it:

regions.swift:23:19: error: sending 'other' risks causing data races
23 |     await archive.store(other)
   |                   `- note: sending 'other' to actor-isolated instance method 'store' risks causing
   |                            data races between actor-isolated and local nonisolated uses
24 |     other.lines.append("oops")  // used after it was sent
   |     `- note: access can happen concurrently

Without the last three lines of build, the program compiles and prints archived report with 1 lines.

This is also why the first example failed: counter was used again by main (to print it) and shared by ten closures at the same time.

sending parameters and results

You can write the same "hand over" contract into your own functions. A sending parameter means the caller gives up the value. The function may then send it to another domain:

final class Buffer {          // not Sendable
    var bytes: [UInt8] = []
}

// 'sending' parameter: the caller gives up the value
func consumeInBackground(_ buffer: sending Buffer) -> Task<Int, Never> {
    Task.detached {
        buffer.bytes.append(0xFF)  // OK: nobody else can reach 'buffer'
        return buffer.bytes.count
    }
}

@main
struct App {
    static func main() async {
        let buffer = Buffer()
        buffer.bytes = [0, 0, 0]
        let task = consumeInBackground(buffer)
        print("bytes after append:", await task.value)
    }
}

Output:

bytes after append: 4

Remove sending from the parameter and the function no longer compiles. The caller might still hold buffer, so capturing it in a detached task is unsafe: error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure. Keep sending but use buffer in main after the call, and the error moves to the caller: note: 'buffer' used after being passed as a 'sending' parameter; Later uses could race.

A sending result says the returned value is not connected to anything the function keeps. This lets an actor create a non-Sendable value and return it (using the same Buffer class):

actor Pool {
    var created = 0
    // the actor creates a new Buffer and hands it over completely
    func make(size: Int) -> sending Buffer {
        created += 1
        let b = Buffer()
        b.bytes = Array(repeating: 0, count: size)
        return b
    }
}

@main
struct App {
    static func main() async {
        let pool = Pool()
        let buffer = await pool.make(size: 3)  // now owned by main
        buffer.bytes.append(1)
        print("buffer has \(buffer.bytes.count) bytes")
    }
}

Output:

buffer has 4 bytes

Without sending, the call fails with error: non-Sendable 'Buffer'-typed result can not be returned from actor-isolated instance method 'make(size:)' to main actor-isolated context.

The standard library uses sending a lot. The closures of Task { }, Task.detached and group.addTask are sending parameters. In Swift 5.x they were @Sendable, which was stricter. Now they may capture non-Sendable values, as long as those values aren't used anywhere else.

Global and static variables

A global or static var can be reached from any thread, so Swift 6 rejects it unless it is protected:

var requestCount = 0

struct Settings {
    static var verbose = false
}

final class Theme { var color = "blue" }
let defaultTheme = Theme()
globals_err.swift:1:5: error: var 'requestCount' is not concurrency-safe because it is nonisolated global shared mutable state
globals_err.swift:4:16: error: static property 'verbose' is not concurrency-safe because it is nonisolated global shared mutable state
globals_err.swift:8:5: error: let 'defaultTheme' is not concurrency-safe because non-'Sendable' type 'Theme' may have shared mutable state

The fixes:

import Synchronization

// 1. make it a constant
let maxRetries = 3

// 2. isolate it to a global actor
@MainActor var requestCount = 0

// 3. protect it with a Sendable wrapper
let hits = Atomic<Int>(0)

// 4. opt out: you guarantee safe access yourself
nonisolated(unsafe) var legacyFlag = false

struct Settings {
    @MainActor static var verbose = false
}

@main
struct App {
    static func main() async {        // main runs on the main actor
        requestCount += 1
        Settings.verbose = true
        legacyFlag = true
        await withTaskGroup(of: Void.self) { group in
            for _ in 0..<100 {
                group.addTask { hits.add(1, ordering: .relaxed) }
            }
        }
        print(maxRetries, requestCount, Settings.verbose, legacyFlag,
              hits.load(ordering: .relaxed))
    }
}

Output:

3 1 true true 100

nonisolated(unsafe) is the variable version of @unchecked Sendable. Use it only when the variable is protected by something the compiler can't see, such as being written once at startup. Top-level variables in a main.swift script are implicitly @MainActor, so they don't need any of this.

Migrating existing code

Turning on Swift 6 mode for a large project can produce hundreds of errors at once. Migrate in steps:

  1. Stay in Swift 5 mode and enable checks as warnings. With swiftc use -strict-concurrency=minimal, targeted or complete. complete reports everything Swift 6 would, as warnings ending with this is an error in the Swift 6 language mode:
swiftc -swift-version 5 -strict-concurrency=complete main.swift

race.swift:11:23: warning: passing closure as a 'sending' parameter risks causing data races
between main actor-isolated code and concurrent execution of the closure; this is an error
in the Swift 6 language mode
  1. Fix module by module, starting with modules that have no dependencies. Make value types Sendable, turn shared mutable classes into actors or protect them with a Mutex, and annotate UI-facing types with @MainActor.
  2. Switch a module to Swift 6 mode once it has no warnings left.

In SwiftPM, these are per-target settings. Here an unmigrated Legacy target stays in Swift 5 mode with complete checking as warnings, and the App target uses Swift 6 mode:

// swift-tools-version: 6.2
import PackageDescription

let package = Package(
    name: "Migrate",
    targets: [
        // old code, not yet migrated: Swift 5 mode, all checks as warnings
        .target(
            name: "Legacy",
            swiftSettings: [
                .swiftLanguageMode(.v5),
                .enableUpcomingFeature("StrictConcurrency"),
            ]
        ),
        // new code: Swift 6 mode (the default for tools version 6.0+)
        // plus the Swift 6.2 approachable-concurrency settings
        .executableTarget(
            name: "App",
            dependencies: ["Legacy"],
            swiftSettings: [
                .defaultIsolation(MainActor.self),
                .enableUpcomingFeature("NonisolatedNonsendingByDefault"),
                .enableUpcomingFeature("InferIsolatedConformances"),
            ]
        ),
    ]
)

@preconcurrency import

Code in Swift 6 mode often depends on a module that hasn't been migrated yet, for example:

// Sources/Legacy/Legacy.swift, written before Sendable existed
public final class Settings {
    public var name: String
    public init(name: String) { self.name = name }
}

public var sharedCounter = 0

Using sharedCounter from the App target is an error: reference to var 'sharedCounter' is not concurrency-safe because it involves shared mutable state. Importing the module with @preconcurrency relaxes the checks for declarations from that module, until its authors add proper annotations:

@preconcurrency import Legacy

nonisolated func describe(_ s: Settings) -> String { "settings: \(s.name)" }

func run() async {
    let settings = Settings(name: "dev")
    let task = Task.detached {
        describe(settings)
    }
    print(await task.value)
    print("counter:", sharedCounter)
}

await run()

swift run output:

settings: dev
counter: 0

The compiler even suggests this itself: warning: add '@preconcurrency' to treat 'Sendable'-related errors from module 'Legacy' as warnings. Remove the attribute once the dependency is updated.

Swift 6.2: approachable concurrency

Swift 6.0 code often ran into errors in programs that didn't need parallelism at all, for example app code that runs entirely on the main thread. Swift 6.2 added settings that make the simple case simple. They are opt-in, so existing code doesn't change behavior. New Xcode 26 app projects turn them on by default.

nonisolated(nonsending) and @concurrent

In Swift 6.0 and 6.1 a nonisolated async function always runs on the global thread pool, even when called from the main actor. So calling an async method of a non-Sendable object from an actor sends the object to another domain:

final class ImageLoader {      // not Sendable
    var loaded: [String] = []
    func load(_ name: String) async {
        try? await Task.sleep(for: .milliseconds(10))
        loaded.append(name)
    }
}

@MainActor
final class ViewModel {
    let loader = ImageLoader()  // owned by main-actor state

    func refresh() async {
        await loader.load("cat.png")
        print("loaded:", loader.loaded)
    }
}

@main
struct App {
    static func main() async {
        await ViewModel().refresh()
    }
}
nonsending2.swift:14:22: error: sending 'self.loader' risks causing data races
   |  `- note: sending main actor-isolated 'self.loader' to @concurrent instance method 'load' risks
   |          causing data races between @concurrent and main actor-isolated uses

The upcoming feature NonisolatedNonsendingByDefault (Swift 6.2) changes the default. A nonisolated async function now runs on the caller's actor, like a synchronous function does. The value never leaves the main actor, so the same code compiles and prints loaded: ["cat.png"]:

swiftc -swift-version 6 -enable-upcoming-feature NonisolatedNonsendingByDefault main.swift

You can also get this per function, without the feature flag, by writing nonisolated(nonsending) func load(_ name: String) async.

When you do want a function to run on the thread pool, for example CPU-heavy work that shouldn't block the main actor, mark it @concurrent. This program prints where each function runs, using the #isolation macro:

final class Document {        // not Sendable
    var text = ""
}

// prints which actor the calling code runs on
func whereAmI(_ isolation: (any Actor)? = #isolation) -> String {
    isolation.map { "\(type(of: $0))" } ?? "global executor"
}

// A plain nonisolated async function.
// Swift 6.0/6.1: always runs on the global concurrent executor.
// With NonisolatedNonsendingByDefault: runs on the caller's actor.
func wordCount(_ doc: Document) async -> Int {
    print("  wordCount runs on:", whereAmI())
    return doc.text.split(separator: " ").count
}

// @concurrent (Swift 6.2): always leaves the caller's actor
@concurrent
func checksum(_ text: String) async -> Int {
    print("  checksum runs on:", whereAmI())
    return text.unicodeScalars.reduce(0) { $0 &+ Int($1.value) }
}

@main
struct App {
    static func main() async {      // isolated to the main actor
        print("main runs on:", whereAmI())
        let doc = Document()
        doc.text = "the quick brown fox"
        print("words:", await wordCount(doc))
        print("checksum:", await checksum(doc.text))
    }
}

Output in plain Swift 6 mode:

main runs on: MainActor
  wordCount runs on: global executor
words: 4
  checksum runs on: global executor
checksum: 1843

Output with -enable-upcoming-feature NonisolatedNonsendingByDefault:

main runs on: MainActor
  wordCount runs on: MainActor
words: 4
  checksum runs on: global executor
checksum: 1843

@concurrent functions still follow the normal rules: arguments must be Sendable or sent. That's why checksum takes the String instead of the Document.

Default MainActor isolation

With -default-isolation MainActor (SwiftPM: .defaultIsolation(MainActor.self)), every declaration in the module that isn't marked otherwise is @MainActor. Single-threaded code then has nothing to check, and you opt into concurrency where you need it:

// compiled with: -default-isolation MainActor

var launchCount = 0               // implicitly @MainActor, so no error

final class Store {               // implicitly @MainActor
    var items: [String] = []
    func add(_ item: String) { items.append(item) }
}

// opt a type out of the default
nonisolated struct Parser {
    func parse(_ line: String) -> [String] {
        line.split(separator: ",").map(String.init)
    }
}

// runs off the main actor
@concurrent
func parseInBackground(_ line: String) async -> [String] {
    Parser().parse(line)
}

@main
struct App {
    static func main() async {
        launchCount += 1
        let store = Store()
        for item in await parseInBackground("apple,pear,plum") {
            store.add(item)
        }
        print(launchCount, store.items)
    }
}

Output:

1 ["apple", "pear", "plum"]

Without the flag, the global var launchCount is an error (nonisolated global shared mutable state). With the flag, the checks still protect you at the boundary: touching launchCount inside the @concurrent function fails with error: main actor-isolated var 'launchCount' can not be mutated from a nonisolated context.

Default MainActor isolation suits app and script targets. For libraries and servers that are meant to run in parallel, the usual choice is to keep the nonisolated default and enable only NonisolatedNonsendingByDefault. InferIsolatedConformances, the third 6.2 setting in the package above, makes a @MainActor type's protocol conformances main-actor-isolated too, so such a type can conform to an ordinary, nonisolated protocol without marking every requirement nonisolated.

Common errors and fixes

Error message (shortened) Typical fix
passing closure as a 'sending' parameter risks causing data races don't share the captured object; use an actor or Mutex, or return values from the task
sending 'x' risks causing data races stop using x after handing it over, or make its type Sendable
capture of 'x' with non-Sendable type 'T' in a '@Sendable' closure make T Sendable, or capture only the Sendable parts
mutation of captured var 'x' in concurrently-executing code capture a copy ([x]), or return the result instead of mutating
stored property 'p' of 'Sendable'-conforming class is mutable make it let, protect it with a Mutex, or use an actor
non-Sendable 'T'-typed result can not be returned from actor-isolated ... make T Sendable, or return it as sending T
var 'x' is not concurrency-safe because it is nonisolated global shared mutable state let, @MainActor, Atomic/Mutex, or nonisolated(unsafe)
errors about types from an old module @preconcurrency import

Summary

Feedback about page:

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



Table Of Contents