How to use a non sendable class with async methods correctly

Generated on 8/12/2024

1 search

To use a non-sendable class with async methods correctly in Swift, you can leverage Swift's concurrency features, particularly actors. Actors are a convenient way to manage shared mutable state safely across different concurrency domains. Here's a brief overview of how you can handle non-sendable classes with async methods:

  1. Understanding Sendability: In Swift, a sendable value is one that can be safely shared across concurrency domains without causing data races. If a class is not sendable, it means it might not be safe to access it concurrently from multiple threads.

  2. Using Actors: Actors in Swift are reference types that automatically protect their state by serializing access. This means that only one task can execute on an actor at a time, which helps prevent data races. If you have a non-sendable class, you can encapsulate it within an actor to manage its state safely.

  3. Asynchronous Access: When you access an actor's methods from outside its context, these calls are asynchronous. You need to use the await keyword to handle these asynchronous calls properly.

For example, if you have a non-sendable class UserStore, you can make it an actor to ensure safe concurrent access:

actor UserStore {
    // Your shared mutable state and methods
}

// Usage
let userStore = UserStore()
await userStore.someMethod()

By making UserStore an actor, you ensure that all accesses to its state are serialized, thus avoiding data races.

For more detailed information, you can refer to the session A Swift Tour: Explore Swift’s features and design (21:38) where actors and their usage are discussed.