'What is the "current actor" in the Swift Concurrency model?

Reading the Concurrency section of the Swift Guide, I came across:

To create an unstructured task that runs on the current actor, call the Task.init(priority:operation:) initializer. To create an unstructured task that’s not part of the current actor, known more specifically as a detached task, call the Task.detached(priority:operation:) class method.

There is the phrase "current actor". This is also mentioned in the documentation of Task.init:

Runs the given nonthrowing operation asynchronously as part of a new top-level task on behalf of the current actor.

Before, I thought I had understood what "current actor" meant:

  • if the code runs on the main queue, then the current actor can be thought of as the MainActor, since its executor is the main queue.
  • if the code is marked with a global actor attribute, then its current actor is that global actor
  • if the code is in an actor and is not nonisolated, then its current actor is that actor.
@SomeOtherActor
func somethingElse() {
    DispatchQueue.main.async {
        // current actor is MainActor
    }
}

@MainActor
class Foo: NSObject {
    func foo() { /* current actor is MainActor */ }
}

actor Bar {
    func foo() { /* current actor is Bar */ }
}

However, recently I realised that I forgot to consider a situation - what happens on a global queue (or any other random queue)?

@SomeOtherActor
func somethingElse() {
    DispatchQueue.global().async {
        // current actor is?
    }
}

When I tried accessing one of the actor-isolated properties of SomeOtherActor in the closure, I get the message:

Property 'x' isolated to global actor 'SomeOtherActor' can not be mutated from a non-isolated context

Is that Swift's way of saying there is no current actor? If so, what will Task.init do? The documentation doesn't really say.

Ideally, is there a way to programmatically print the current actor?

I thought the SE proposals would explain what "current actor" meansNone of the SE proposals mention the word "current actor": SE-0306, SE-0313, SE-0316, SE-0327, SE-0344.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source