← Back to Swift Course | Chapter 13: Concurrency | Lesson 4 of 6

MainActor

MainActor is a special label that means "this code must run on the main thread," which is important for anything touching the screen.

Marking a Function with @MainActor

A function annotated @MainActor is guaranteed to run on the main actor's thread, which callers from other contexts must await to switch into.

Example: Marking a Function with @MainActor

markup
@MainActor
func updateStatus(_ message: String) {
    print("Status updated on main actor: \(message)")
}

await updateStatus("Ready")

A MainActor-Isolated Property

An entire type or a specific property can be isolated to the main actor, ensuring all access to it is properly synchronized to the main thread.

Example: A MainActor-Isolated Property

markup
@MainActor
class ViewState {
    var title: String = "Loading"
}

let state = await ViewState()
await MainActor.run {
    state.title = "Loaded"
}
let title = await state.title
print(title)
Common Mistakes
  1. Forgetting UI-related code in a real app must run on the main thread; @MainActor enforces this at compile time.
  2. Applying @MainActor to heavy computational work, which unnecessarily forces it onto the main thread instead of a background context.
  3. Assuming @MainActor code runs synchronously from any context without await; calling it from a non-main-actor context still requires awaiting the hop.
Chapter Summary
  • @MainActor marks a function, property, or type as required to run on the main thread.
  • It's essential for any code that must run in careful ordered fashion, such as UI updates in real apps.
  • Calling @MainActor code from outside the main actor's context requires await.
  • @MainActor is Swift's structured replacement for manually dispatching work to the main queue.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.