2

When using DispatchQueue.main as a parameter/variable it's impossible to satisfy the @MainActor requirements.

See the following code:

final class MyClass {
    init() {
        DispatchQueue.main.async {
            self.someMainFunction() // legal
        }

        let queue = DispatchQueue.main
        queue.async {
            assert(Thread.isMainThread) // true
            self.someMainFunction() // Call to main actor-isolated instance method 'someMainFunction()' in a synchronous nonisolated context
        }

        queue.async { @MainActor in // Converting function value of type '@MainActor () -> ()' to '@convention(block) () -> Void' loses global actor 'MainActor'
            assert(Thread.isMainThread) // true
            self.someMainFunction()
        }

        // or another example

        doSomethingAsync(queue: .main) { [weak self] in
            assert(Thread.isMainThread) // true
            self?.someMainFunction() // Call to main actor-isolated instance method 'someMainFunction()' in a synchronous nonisolated context
        }
    }

    func doSomethingAsync(queue: DispatchQueue, something: @escaping () -> Void) {
        queue.async {
            something()
        }
    }

    @MainActor
    func someMainFunction() {
    }
}

Any ideas for workarounds? The only thing I've found is using @MainActor(unsafe) on someMainFunction() but I really don't want to do that.

2
  • Why not just use Task.detached { @MainActor in ... }? Commented Feb 5, 2022 at 18:46
  • @BradleyMackey legacy code predating Tasks. But this appears to be a unfixable scenario and a gross oversight by the Swift team :( Commented Feb 6, 2022 at 15:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.