Non-isolated context error in actor's init

I run into strange issue, which doens't make sence for me.

Code below trigger error - "Main actor-isolated class property 'willEnterForegroundNotification' can not be referenced from a non-isolated context"

actor MyActor {
    init() {
        NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)
    }
}

This error make no sense for me. Here why:

So UIApplication marked with @MainActor, which sounds correct.
Because of this, its static property is also Main actor only, because may be it uses smth, that has main thread usage only too, which is... may be understandable.
But issue here that actor init is sync methos, not async. I can check it by adding nonisolated keyword to it and getting warning 'nonisolated' on an actor's synchronous initializer is invalid; this is an error in Swift 6

It means, while in init we are not in isolated context to any actor, we are in usual sync code and this is my responsibility to make sure that I call method from main thread only, so UIApplication.willEnterForegroundNotification worked properly. Issue here, from my POV, that sync actor init is not async code and should not trigger any check for context at all.
Because I can do a simple workaround:

extension NotificationCenter {
    var appWillEnterForegroundPublisher: NotificationCenter.Publisher {
        publisher(for: UIApplication.willEnterForegroundNotification)
    }
}

actor MyActor {
    init() {
        NotificationCenter.default. appWillEnterForegroundPublisher
    }
}

This code not triggering any error. And my expectation that initial code should not trigger error about context too, because actor's init doesn't have any context yet... And should be treated as normal sync code.

1 Like