swifttaskactorswift-task

Getting "Unknown attribute 'MainActor'" when using MainActor with Task


Task { @MainActor // ERROR: Unknown attribute 'MainActor'
    handleSuccess(of: response)
}

I thought you can use actors on Tasks. Not sure what I'm doing wrong.


Solution

  • The error is misleading. Took me a few minutes to figure it out 🙃

    You just need to add in after the actor. Like this:

    Task { @MainActor in
        handleSuccess(of: response)
    }