How do I use sendable?

Asked on 08/04/2024

1 search

To use Sendable in Swift, you need to understand that it is a protocol that ensures a type can be safely transferred between different concurrency domains, such as actors or tasks. Here are the key points on how to use Sendable:

  1. Automatic Conformance for Internal Types: For internal types, Swift automatically considers them Sendable if they meet the criteria. This means they do not contain any mutable state that could lead to data races.

  2. Explicit Conformance for Public Types: 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 that could lead to data races. You can do this by adding the Sendable protocol conformance to your type.

    public struct MyType: Sendable {
        // Your properties and methods here
    }
    
  3. Handling Warnings: When you mark a type as Sendable, it can eliminate multiple warnings related to data race safety. This is particularly useful in large projects where multiple parts of the codebase might require the type to be Sendable.

  4. Dealing with Non-Sendable Types: If you encounter a type that cannot be marked as Sendable (e.g., an Objective-C type that stores mutable state), you need to make decisions about safety. One option is to reason about the type and ensure it is safe to use in a concurrent context, even if it is not Sendable.

For a practical example and more detailed explanation, you can refer to the session Migrate your app to Swift 6 (32:27).

Relevant Sessions

These sessions provide a comprehensive overview of how to work with Sendable and ensure data race safety in your Swift applications.