MainActor
MainActor
is a special actor that is tied to the system level and is always present in a modern Apple app, that is based on a version of the operating system that is capable of supporting structured concurrency.
MainActor is tied to the main queue. Any update to the UI in Apple systems needs to be performed within the main queue.
Any code marked with @MainActor
will execute on the MainActor
, which is tied to the main queue, and this is particularly useful to ensure that UI update-related code is not executed on threads different from the main one.
For instance, the code shown in the following fragment would be executed in MainActor
:
@MainActor private func showAlert() { isAlertShown = true }
And this would be needed if we wanted to be able to, for example, invoke the showAlert()
function from a within background task, but with the need to affect the UI.
@MainActor
can be used with closures, classes, structs...