Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 146 ยท Concurrency

Sendable and Data Races

Understand Swift's Sendable protocol - which types may cross between tasks and actors, @Sendable closures, sending parameters, @unchecked Sendable with Mutex, and the real Swift 6 data-race errors.

Every concurrency lesson so far has hinted at one rule: not everything may be shared between tasks. An Int can be copied to another task without any risk. A plain class instance with a mutable property cannot, because two tasks would then hold the same object and could change it at the same time. Swift 6 turns that intuition into a type-system feature called Sendable, and it turns breaking it into a compile error.

This lesson explains what Sendable promises, which types have it automatically, how to make your own types conform, what a @Sendable closure is, what the newer sending keyword adds, and how to read the error messages. It builds on Tasks, Task groups and Actors.

What is a data race?

A data race happens when two threads access the same memory at the same time, at least one of them writes, and there is no synchronization between them. The outcome is undefined: wrong numbers, corrupted arrays, crashes. Data races are especially nasty because they depend on timing, so the same program can work a thousand times and then fail once in production.

Most languages leave you to find these bugs with testing and luck. Swift 6 in its default language mode, the one used by every example on this site, checks for them at compile time. The check is called strict concurrency checking, and Sendable is its vocabulary.

The compiler is checking for possible races from the way values move between isolation domains: the main actor, other actors, and ordinary non-isolated code that may run on any thread. Moving a value from one domain to another is called crossing a boundary, and only Sendable values may cross freely.

The Sendable protocol

Sendable is a protocol with no requirements. Conforming to it is a promise that values of this type can be safely used from several concurrent contexts at once. The compiler verifies the promise for you whenever it can.

Types that are Sendable automatically:

  • Numbers, Bool, String, Character, Date, UUID, URL, and other simple value types in the standard library and Foundation.
  • Arrays, dictionaries, sets and optionals whose elements are Sendable.
  • Tuples whose elements are Sendable.
  • Functions marked @Sendable, and actors.
  • Structs and enums whose stored properties and associated values are all Sendable, as long as they are not public (public types must declare it, because the compiler cannot see across module boundaries).

You rarely write anything to get this for your own value types:

Swift Value types are Sendable by inference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints the value, and the second prints 3. A detail you will notice in the first line: the runner on this site prints type names as binary.Point, because the single file is compiled as a module called binary. The important part is that describe requires T: Sendable, and Reading satisfies it without us writing the word, so we could also hand it to a detached task.

Why are value types safe? When a struct crosses into another task it is copied. Each task has its own copy, so a change in one is invisible to the other. There is nothing shared, so there can be no race.

Types that cannot be Sendable

Classes are the problem, because a reference is a pointer to shared state. A class may conform to Sendable only if it cannot be changed after creation: it must be final, have only let properties, and every property must itself be Sendable. Break the rules and the compiler tells you which one:

Swift A mutable property in a Sendable class (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The real message is main.swift:3:9: error: stored property 'volume' of 'Sendable'-conforming class 'Settings' is mutable. Change var volume to let volume and it compiles. A struct can fail in a similar way when one property holds a non-Sendable value:

Swift A non-Sendable property in a Sendable struct (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is main.swift:6:9: error: stored property 'plain' of 'Sendable'-conforming struct 'Holder' has non-Sendable type 'Plain'. The check is deep: a type is only as safe as the least safe thing inside it.

An immutable class is perfectly fine, and it is also a useful design. Reference semantics without mutation means no race:

Swift An immutable final class is Sendable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

It prints 3. The detached task uses settings and no race is possible, because nobody can change it.

What the error looks like in practice

You will meet Sendable errors mostly when a non-Sendable value is captured by a closure that runs concurrently. Here is a class with a mutable property, used from a detached task:

Swift Capturing a non-Sendable object (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports main.swift:6:23: error: non-Sendable type 'Box' of let 'box' cannot exit main actor-isolated context and a second error saying that the main actor-isolated let 'box' cannot be accessed from outside of the actor. Read the first one as: "Box is not safe to share, and you are trying to move it out of the main actor into a task that runs somewhere else." Your options, from best to worst:

  1. Make the type a struct or enum (copy semantics).
  2. Make it an actor, then call it with await.
  3. Make it an immutable final class that conforms to Sendable.
  4. Protect the data with a lock and use @unchecked Sendable (below).
  5. Keep it on one actor (@MainActor) and await its members.

@Sendable closures

A closure can also cross boundaries: you pass it to Task.detached, addTask or your own functions that run it elsewhere. Swift therefore has @Sendable closures. Such a closure may only capture values that are Sendable, and it may not mutate captured variables.

Swift A @Sendable closure that mutates a local (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is main.swift:7:16: error: mutation of captured var 'count' in concurrently-executing code. The closure may run later, on another thread, while demo reads count itself. To pass data back, return it from the task, or send it into an actor.

Closures that capture only Sendable values work, and Swift often infers @Sendable for you when you pass a closure to an API that requires it. You can also store @Sendable function values in Sendable structs:

Swift A Sendable struct holding a @Sendable closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The three jobs multiply 10 by 1, 2 and 3, and the program prints 60. Each closure captures only an immutable Int, so the struct stays Sendable.

Sendable and generics

Generic APIs ask for Sendable too. If you write a function that hands a value of type T to another task, constrain it: func process<T: Sendable>(_ value: T) async. Task groups require their child result type to be Sendable, which is why withTaskGroup(of: Int.self) is fine and withTaskGroup(of: SomeClass.self) is not unless the class is.

The sending keyword

Sendable is a property of a type. Sometimes a type is not Sendable, but one particular value is safe to hand over because the sender gives it up and never touches it again. Swift 6 can check that with the sending keyword on a parameter or result.

Swift Handing an object over with sending

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Draft is a mutable class and is not Sendable, yet this compiles and prints published: hello. The compiler tracks that draft was created locally, nothing else points to it, and publish takes ownership. Now see what happens if the sender keeps using the object:

Swift Using a value after sending it (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is main.swift:12:11: error: sending 'draft' risks causing data races, with notes that 'draft' used after being passed as a 'sending' parameter and that the later access can happen concurrently. The idea behind it is called region-based isolation: the compiler follows where a value came from, and if it is still in a private region, nobody else can have a reference, so transferring it is safe. You do not need to master the theory; remember the practical rule: after you hand an object over, treat it as gone.

Escape hatches, with care

Sometimes you know something the compiler cannot prove. Swift gives you ways to say so. They remove the compiler's protection, so each is a promise you must keep yourself.

@unchecked Sendable says "trust me, this class is thread-safe". Use it when you protect the mutable state with a lock. The standard library has Mutex in the Synchronization module, and a class whose only mutable state sits inside a Mutex can be plain Sendable, because Mutex itself is Sendable:

Swift A Sendable class built on Mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

It prints 50. No @unchecked was necessary here, because the only stored property is a let holding a Mutex. Reach for @unchecked Sendable only when the compiler genuinely cannot see why your type is safe, for example when wrapping an old class from a library that is thread-safe but not annotated. We cover locks and atomics in Synchronization and Shared State.

nonisolated(unsafe) switches off checking for a single variable. It is meant for legacy global state you cannot yet restructure:

Swift nonisolated(unsafe) turns the check off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program compiles and prints compiled and ran, but nothing protects legacyCounter anymore, and two tasks calling bump() at once would race. Treat every unsafe or unchecked in a code base as a debt to pay back later with an actor or a Mutex.

Global variables under Swift 6

Because any code in any task can reach a global, Swift 6 is strict about them. A global or static constant of a Sendable type is fine. A global variable must be isolated to an actor (the top-level variables in main.swift are, to the main actor) or be marked nonisolated(unsafe):

Swift A mutable static property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler accepts global (main-actor isolated, since it is in top-level code) and shared (a constant), but rejects the static property: main.swift:5:16: error: static property 'count' is not concurrency-safe because it is nonisolated global shared mutable state. The message names three fixes: make it a let, isolate it to a global actor such as @MainActor, or use nonisolated(unsafe) if you take responsibility.

Actor-isolated values

Types isolated to a global actor are Sendable automatically, because the actor serializes access to them. That is why you can pass a @MainActor class reference into another task, and why reading its members from there needs await:

Swift A MainActor class used from a detached task

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is home. The class is mutable, but only the main actor touches title; the detached task has to hop there with await.

Language modes and migration

Swift 6 can compile older code in Swift 5 language mode, where these problems are mostly warnings (or nothing at all unless you opt into extra checking). The compiler on this site always uses Swift 6 mode, so you see real errors. When migrating a big project, teams usually turn on strict checking one module at a time with the -strict-concurrency setting, first as warnings, then as errors. The Swift evolution lesson lists the versions and modes, and Common Swift Mistakes covers the errors you will see most.

Practical advice

  • Prefer structs and enums for data that moves between tasks.
  • Put shared mutable state in an actor, and keep the actor small.
  • Make classes final with let properties when they just carry data.
  • Use @MainActor for anything that belongs to the user interface.
  • Treat @unchecked Sendable and nonisolated(unsafe) as last resorts, with a comment explaining why they are safe.
  • Read the first error in a list; the later ones are often consequences.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does conforming to Sendable promise?

    Sendable is about safety across concurrency boundaries, not about networking or serialization. The compiler checks the promise where it can.
  2. 2. Which type is Sendable without any annotation (internal, non-public)?

    Structs and enums are inferred Sendable when everything inside them is Sendable. Mutable classes, and classes that are not final, are not.
  3. 3. Why does a @Sendable closure not allow count += 1 on a captured local var?

    A @Sendable closure can run later and elsewhere, so mutating a captured variable could race with the original owner. Return values or use an actor.
  4. 4. What is the effect of the sending keyword on a parameter?

    With sending, the compiler checks that the value is not used again by the caller (or anything else) after it is handed over, so a transfer is safe.
  5. 5. When is @unchecked Sendable appropriate?

    It switches off the compiler's check, so it is a promise from you. Use it only when the type really is thread-safe, such as state guarded by a lock.

Summary

  • A data race is unsynchronized concurrent access with at least one write; Swift 6 rejects code that could have one at compile time.
  • Sendable marks types whose values can safely cross between tasks and actors. Value types of Sendable parts are Sendable automatically; classes must be final with only immutable Sendable properties.
  • @Sendable closures may only capture Sendable values and may not mutate captured variables.
  • sending lets you hand over a non-Sendable value when the sender never touches it again (region-based isolation).
  • Actors and global-actor-isolated types are Sendable; use await to reach their state.
  • @unchecked Sendable and nonisolated(unsafe) are unchecked promises: use them sparingly, preferably with a Mutex or an actor behind them.
  • Global mutable variables and static properties must be isolated to an actor, be constants, or be explicitly marked unsafe.

Next: AsyncSequence and AsyncStream shows how to consume values that arrive over time.