how make class sendable

Asked on 10/17/2024

1 search

To make a class sendable in Swift, especially when dealing with public types, you need to explicitly mark the type as Sendable. This is because Swift does not automatically infer sendability for public types, as marking a type sendable is a guarantee to your clients that the type contains no mutable state. Here's a brief overview of the process:

  1. Identify the Type: Determine if the type you want to make sendable is a public type. If it's an internal type, Swift might automatically consider it sendable.

  2. Mark as Sendable: For public types, you need to explicitly conform to the Sendable protocol. This involves adding a conformance declaration to your type.

  3. Consider Mutable State: Ensure that the type does not contain mutable state that could lead to data races when accessed concurrently. If the type is a struct with immutable properties, it can typically be made sendable.

  4. Recompile and Check: After marking the type as sendable, recompile your code to check for any additional types that might need to be marked as sendable.

For more detailed guidance, you can refer to the session Migrate your app to Swift 6 (32:27) where this topic is discussed in the context of migrating to Swift 6 and ensuring data-race safety.