Sitemap

What is Sendable in Swift ? Concurrency Without Data Races

Learn how Sendable ensures thread safety in Swift concurrency, when to use it, and how to avoid common pitfalls.Sendable in Swift

2 min readMar 13, 2025

--

Sendable is a protocol introduced in Swift to ensure that types can be safely passed across concurrency domains (e.g., between tasks in Swift concurrency).

1. What Does Sendable Do?

It marks a type as safe to be shared across multiple threads, ensuring no data races in concurrent environments.

2. When to Use It?

  • When working with Swift Concurrency (async/await, Task, Actor).
  • When a type is used across different isolated execution contexts (like different tasks or actors).

3. Example Usage

✅ Sendable Struct (Automatic Conformance)

Value types (structs, enums) that contain only Sendable types automatically conform to Sendable:

struct User: Sendable {
let name: String
let age: Int
}

❌ Non-Sendable Class (Reference Types Need Manual Handling)

Classes do not conform to Sendable by default, because they introduce shared mutable state.

class User { // ❌ Not Sendable
var name: String
init(name: String) {
self.name = name
}
}

To fix this, either:

  1. Make it immutable (final + let properties)
  2. Mark it explicitly @unchecked Sendable (⚠️ You promise it's thread-safe)
final class User: @unchecked Sendable {
let name: String
init(name: String) {
self.name = name
}
}

4. Sendable and Actors

Actors isolate state and are implicitly Sendable, so they can be safely used across threads.

actor Counter {
private var value = 0
func increment() { value += 1 }
}

5. Common Errors

If a type is used in an async function or within an actor and is not Sendable, Swift will give an error like:
🚨 "Type 'X' is not Sendable; this is an error in Swift concurrency."

6. Summary

Sendable is a crucial tool for writing safe concurrent code in Swift. By marking types as Sendable, you prevent data races and ensure smooth execution across multiple threads. Structs and enums are usually safe by default, while classes require extra care. Understanding and using Sendable correctly will make your Swift concurrency code more reliable and efficient. 🚀

Follow for more …

--

--

Brahim Siempay
Brahim Siempay

No responses yet