I have the following SwiftUI Observable model class along with a local & global actor variables that fails to build with the error Global actor 'MyGlobalActor'-isolated default value in a nonisolated context
. My question is what is special about global actor that build fails but build succeeds for local actor? Does the init method in local actor runs on default context but the global actor runs in isolated context?
import SwiftUI
@Observable
final class Model {
let testActor = TestLocalActor() //This builds
let testGlobalActor = TestGlobalActor() //Build fails here
}
actor TestLocalActor {
init() {
}
}
@MyGlobalActor
final class TestGlobalActor {
init() {
}
}
@globalActor
actor MyGlobalActor: GlobalActor {
static let shared = MyGlobalActor()
}
Does the init method in local actor runs on default context but the global actor runs in isolated context?
Correct. More accurately, non-async
initialisers of actor
s are considered non-isolated (see also), whereas once you isolate the whole class to a global actor, the class' init
is also isolated to the global actor.
You can add the nonisolated
modifier to the init
, if you want to exclude it from the global actor's isolation.
@MyGlobalActor
final class TestGlobalActor {
nonisolated init() {
}
}
@Observable
final class Model {
let testGlobalActor = TestGlobalActor() // now this compiles
}