While adapting to the new concurrency, I encountered with an issue: a seemingly constant, unchanging value can be accessed only on the @MainActor
:
final class MyClass {
let myValue: NSNotification.Name
@MainActor
init() {
myValue = UIWindow.didBecomeKeyNotification
}
}
Without having the init running on @MainActor
we would get an error saying:
final class MyClass {
let myValue: NSNotification.Name
init() {
myValue = UIWindow.didBecomeKeyNotification // Main actor-isolated class property 'didBecomeKeyNotification' can not be referenced from a non-isolated context
}
}
Which makes sense since the UIWindow
is marked as @MainActor
:
@MainActor open class UIWindow : UIView {...}
But I found this weird, since the didBecomeKeyNotification
is a constant value:
public class let didBecomeKeyNotification: NSNotification.Name
Please correct me if I am missing something, but it does not make sense to restrict it only to the main thread. Why we can't access the value on some background thread as well ? In my opinion it would be safe.
Same applies to other, more often used properties such as: UIScreen.main.nativeBounds
, UIScreen.main.scale
etc. Those are not a let
but a var
value, but still we can consider them a constant, as they won't change. Now if we have a big codebase, and we convert all the code that uses the above mentioned "constant" values, to only run on the @MainActor
, it will start a chain reaction. Eventually we end up with lot of functions and and class initialisation, which will run on the @MainActor
, occupying the main thread, because of just reading a constant value, while I feel it could easily run on some free background thread.
So coming from this I was thinking, is there a way to tell the compiler: I know a specific value may be marked to be accessed only from the @MainActor
, but despite of that I want to access it on a background thread ?