where should i use sendable?

Asked on 08/03/2024

1 search

You should use Sendable in Swift when you need to ensure that a type can be safely shared between different concurrency domains, such as actors or tasks. Here are some specific scenarios where Sendable is relevant:

  1. Public Types: If you have a public type that you share outside of your module, you need to explicitly mark it as Sendable. Swift does not infer sendability for public types automatically because marking a type as Sendable is a guarantee to your clients that the type contains no mutable state. This is important to avoid locking in sendability prematurely (Migrate your app to Swift 6).

  2. Concurrency Safety: To avoid data races, Swift requires that values shared between concurrency domains are Sendable. A Sendable value protects its state from concurrent accesses. For example, a type might qualify as Sendable if it acquires a lock while reading and writing mutable state (A Swift Tour: Explore Swift’s features and design).

  3. Actors: When working with actors, you might need to send data between different actors. If the data type is a reference type, it could lead to potential data races. By marking the type as Sendable, you ensure that it can be safely shared between actors (Migrate your app to Swift 6).

Relevant Sessions

If you need more detailed guidance on specific scenarios or examples, you can refer to the sessions mentioned above.