How to initialize global actor marked instance properly?

Hello

I am experimenting with actors, and global actors in particular and I observe a behaviour which I do not quite understand. In the code below I have defined a simple actor and a class that belongs to a global actor. When trying to initialize them synchronously on the @MainActor, the normal actor code works with no issues but the global actor class instance produces an error

Call to global actor 'MyGlobalActor'-isolated initializer 'init(number:)' in a synchronous main actor-isolated context

Here is the code

actor Simple {
  var number: Int

  init(number: Int) {
    self.number = number
  }
}

// MyGlobalActor definition is omitted to make this example simpler
@MyGlobalActor class PartOfGlobal {
  var number: Int

  init(number: Int) {
    self.number = number
  }
}

@MainActor func initializer() {
  let simple = Simple(number: 1)
  let global = PartOfGlobal(number: 1) // compiler error here
}

Is this a bug or an expected behavior?
If it is not a bug, is there some way to initialize instances from a global actor without creating a Task (synchronously) ?

BR
Filip

The problem here is that since your type is marked @MyGlobalActor, all of its members are only synchronously accessible on that actor. However, you can mark the initializer as a nonisolated init to allow it to be called from any context. Once you do that, you will no longer be able to access actor-isolated properties or methods synchronously from the initializer, but you should still be able to set an initial value for all properties.

1 Like