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
@MainActor
func updateStatus(_ message: String) {
print("Status updated on main actor: \(message)")
}
await updateStatus("Ready")
Login to try C/C++/Java/PHP code in the editor
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
@MainActor
class ViewState {
var title: String = "Loading"
}
let state = await ViewState()
await MainActor.run {
state.title = "Loaded"
}
let title = await state.title
print(title)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting UI-related code in a real app must run on the main thread;
@MainActorenforces this at compile time. - Applying
@MainActorto heavy computational work, which unnecessarily forces it onto the main thread instead of a background context. - Assuming
@MainActorcode runs synchronously from any context withoutawait; calling it from a non-main-actor context still requires awaiting the hop.
Chapter Summary
@MainActormarks 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
@MainActorcode from outside the main actor's context requiresawait. @MainActoris 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: