DevPrep

All topics › Swift Concurrency (async/await, actors)

What is @MainActor?

Middle PRO

The essence

@MainActor is a global actor whose executor is the main thread (the main queue). By marking a type, method, property or closure @MainActor you tell the compiler: this code is isolated to the main thread. From another isolation it can be called only via await, and the compiler inserts the switch itself. It is a static guarantee: a violation is a compile error, not a runtime crash.

All UI (UIView, UIViewController, SwiftUI View) is already @MainActor, so trying to update it from a background task will not compile in Swift 6.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store