swiftisolationmainactor

Cannot initialize MainActor isolated class from another


I have this little piece of code that won't compile due to Call to main actor-isolated initializer 'init(username:)' in a synchronous nonisolated context.

I don't understand, since as you'll see both classes are annotated with @MainActor, and I tried adding it to the constructor of GlobalState just in case, also didn't work.

Any idea what's going on here? Would appreciate an explanation as well as a solution.

Thanks!

import SwiftUI

@MainActor
public final class User: ObservableObject {
    @Published public var username: String
    
    public init(username: String) {
        self.username = username
    }
}

@MainActor
public final class GlobalState: ObservableObject {
    @Published public var user: User
    
    public init(user: User = .init(username: "safd")) { // error here
        self.user = user
    }
}

enter image description here


Solution

  • This is a known limitation that was fixed in Swift 5.10 as part of SE-0411.

    You need to enable the IsolatedDefaultValues upcoming feature by passing -enable-upcoming-feature IsolatedDefaultValues to the OTHER_SWIFT_FLAGS build setting. For more information, see Using upcoming feature flags.

    Before Swift 5.10, default input arguments were always nonisolated, which means you weren't able to use actor isolated types as default input arguments. SE-0411 solved this by making sure that if a method is actor isolated, its default input arguments are called from that actor as well.