Jack Guo
Jack Guo

Reputation: 4664

Call to main actor-isolated instance method XXX in a synchronous nonisolated context

I am trying to add an async do/catch/defer action to a UIButton. However, if I just call a method in the defer block, I get Call to main actor-isolated instance method XXX in a synchronous nonisolated context error. The workaround I found is to wrap it in another Task block, like the following. Just want to check if this is the correct way to do it? It'd be good if someone can explain what that error message actually says.

@objc private func post(_ sender: UIButton) {
    Task {
        // defer { dismiss(animated: true) } -- Doesn't work
        defer { Task { await dismiss(animated: true) } }
        do {
            try await doSomethingAsync()
        } catch {
            print(error)
        }
    }
}

Upvotes: 40

Views: 41554

Answers (1)

Soumya Mahunt
Soumya Mahunt

Reputation: 2762

This is bug in current swift versions as compiler is not able to recognize the global actor context for a defer block, the discussion for this is going on swift forum and a PR with fix also available that should resolve this issue in future swift versions. For now, explicitly global actor context need to be provided for code to compile:

defer { Task { @MainActor in dismiss(animated: true) } }

Upvotes: 22

Related Questions