Sendable and thread-safety checking
Mark data as Sendable , write @Sendable closures, and choose between value types, actors, and @unchecked Sendable for thread-safe sharing.
What is Sendable?
Sendable is Swift’s way to ensure data is safe to pass between concurrent tasks/actors.
- Most structs/enums are Sendable automatically.
- Classes are not Sendable by default.
- Use actors or @unchecked Sendable (rare, with manual safety).
Value types are easy
Structs with Sendable members are Sendable; passing them between tasks is safe.
// Value types with value-only stored properties are Sendable.
// They are safe to transfer across tasks.
struct Point: Sendable { let x: Int; let y: Int }
func shift(_ p: Point) -> Point { Point(x: p.x + 1, y: p.y + 1) }
// Use in parallel tasks
Task {
let p = Point(x: 1, y: 2)
async let a = shift(p)
async let b = shift(p)
let (p1, p2) = await (a, b)
print(p1, p2) // Point(x: 2, y: 3) Point(x: 2, y: 3)
}All lessons in this course
- TaskGroup for parallelism
- Actors & data isolation, nonisolated
- Sendable and thread-safety checking