what's sendable and give an example of it and compare it with a usecase where we are not using sendable

Asked on 12/10/2024

1 search

In Swift, "Sendable" is a protocol that ensures a type can be safely transferred across concurrency domains without causing data races. A type is considered sendable if it protects its state from concurrent accesses, which is crucial for maintaining data integrity in concurrent programming.

Example of Sendable

Consider a scenario where you have a Drink type that you want to send between different actors in a Swift application. If Drink is a struct with immutable properties, it can be marked as sendable, allowing it to be safely shared between actors without risking data races. Here's a simplified example:

struct Drink: Sendable {
    let name: String
    let size: Int
}

In this case, marking Drink as Sendable ensures that it can be safely passed between actors, as it contains only immutable state.

Use Case Without Sendable

If you have a type that contains mutable state, such as a reference type with properties that can change, it might not be safe to mark it as sendable. For instance, an Objective-C type that stores mutable state in a reference type might not be sendable. In such cases, you would need to ensure thread safety manually, perhaps by using locks or other synchronization mechanisms, or by redesigning the type to avoid shared mutable state.

Comparison

  • With Sendable: Types are explicitly marked as safe for concurrent use, reducing the risk of data races and making the code easier to reason about.
  • Without Sendable: You must manually ensure thread safety, which can be error-prone and complex, especially in large projects.

For more details on how Swift handles sendability and data race safety, you can refer to the session Migrate your app to Swift 6.