1

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 ?

πter
  • 1,899
  • 2
  • 9
  • 23
  • I tried adding the MyClass without the @MainActor and no compiler error is reported. Is there any more configuration setup you have done? You may have enabled SWIFT_STRICT_CONCURRENCY swift compiler option. Also take a look at this one: https://stackoverflow.com/questions/75302715/are-extensions-of-mainactor-classes-on-the-main-actor – Kwnstantinos Nikoloutsos Jul 19 '23 at 22:50
  • If you don’t think something should be isolated to the main actor, feel free to post [feedback](https://feedbackassistant.apple.com/). But unless they change it, it is what it is. – Rob Jul 20 '23 at 03:32
  • @KwnstantinosNikoloutsos yes, I am using a complete checking. Rob I see. Thanks ! – πter Jul 20 '23 at 07:28

0 Answers0