explain sendable

Asked on 08/08/2024

1 search

In Swift, the concept of "sendable" is crucial for ensuring data-race safety in concurrent programming. A type is considered sendable if it can be safely transferred between different concurrency domains, such as actors or threads, without causing data races. Here are some key points about sendable from the WWDC sessions:

  1. Explicit Sendable Conformance:

    • For internal types, Swift can automatically infer sendability. However, for public types, you need to explicitly mark them as sendable. This is because marking a type as sendable is a guarantee to your clients that the type contains no mutable state (Migrate your app to Swift 6).
  2. Data-Race Safety:

    • In Swift 6, the data-race safety of your program is fully verified at compile time. This is achieved by requiring that values shared between concurrency domains are sendable. A sendable value protects its state from concurrent accesses (A Swift Tour: Explore Swift’s features and design).
  3. Practical Example:

    • If you have a type that is a struct with immutable properties, it can be made sendable. This allows you to store the type in one actor and send it to another actor without risking data races (Migrate your app to Swift 6).
  4. Handling Non-Sendable Types:

    • If you encounter a type that cannot be made sendable, such as an Objective-C type that stores mutable state, you may need to make choices about safety. This could involve reasoning about the type's usage or adding synchronization manually (Migrate your app to Swift 6).
  5. Actors and Sendable:

By understanding and utilizing the sendable protocol, you can ensure that your Swift code is safe and free from data races when dealing with concurrency.