swift-concurrency

With Swift Concurrency, is there a way to define a shared actor used across multiple classes, like MainActor?


Is there a mechanism, like the @MainActor tag, where we can specify a shared non-main thread that designated classes are on?

I would like to be able to setup something like:

@AnimalsActor
final class Dog {
    // ...
}

@AnimalsActor
final class Cat {
    // ...
}

Where all the property access and function calls for Cat and Dog would be done on the same actor.

The solutions I have seen require defining an actor then explicitly calling out to it from within the classes, which means frequent context switches between the classes and the actor, rather than the classes being in the context of the actor already.


Solution

  • You can define a global actor. As that Swift Evolution proposal says:

    This proposal introduces global actors, which extend the notion of actor isolation outside of a single actor type, so that global state (and the functions that access it) can benefit from actor isolation, even if the state and functions are scattered across many different types, functions and modules.

    Thus, you can define AnimalsActor as follows:

    @globalActor
    actor AnimalsActor {
        static let shared = AnimalsActor()
    }
    

    And Cat and Dog outlined in your question will work as written:

    @AnimalsActor
    final class Dog {
        // ...
    }
    
    @AnimalsActor
    final class Cat {
        // ...
    }