when to use sendable

Asked on 08/09/2024

1 search

In Swift, the Sendable protocol is used to ensure that a type can be safely transferred between different concurrency domains, such as actors or threads. Here are some key points on when to use Sendable:

  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 to avoid locking in sendability prematurely (Migrate your app to Swift 6).

  2. Concurrency Safety: When you need to ensure data-race safety in your program, especially when values are shared between concurrency domains. 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 using actors, which are reference types that can encapsulate shared mutable state, you might need to make certain types Sendable to ensure safe interaction between different actors (Migrate your app to Swift 6).

  4. Internal Types: For internal types, Swift can automatically consider them Sendable if they meet the criteria. However, for public types, you need to explicitly add Sendable conformance (Migrate your app to Swift 6).

Relevant Sessions

These sessions provide detailed explanations and examples of when and how to use Sendable in your Swift applications.