Global actors help keep your app's main work safe and organized by making sure certain code runs only on the main thread. This is important for updating the user interface smoothly.
0
0
Global actors (@MainActor) in Swift
Introduction
When you want to update the app's user interface safely.
When you need to run code that must not run at the same time as other main thread tasks.
When you want to mark functions or properties to always run on the main thread.
When you want to avoid bugs caused by running UI code on background threads.
Syntax
Swift
@MainActor func yourFunction() { // code that runs on the main thread }
@MainActor is a built-in global actor in Swift for the main thread.
Use it before functions, properties, or classes to ensure they run on the main thread.
Examples
This function will always run on the main thread.
Swift
@MainActor func updateUI() { print("Updating UI on main thread") }
The property and function are marked to run on the main thread, keeping UI data safe.
Swift
class ViewModel { @MainActor var title: String = "" @MainActor func changeTitle(newTitle: String) { title = newTitle } }
The whole class runs on the main thread, so all its methods do too.
Swift
@MainActor class ViewController { func showAlert() { print("Showing alert on main thread") } }
Sample Program
This program shows a function marked with @MainActor to update UI safely. The async function calls it with await to ensure it runs on the main thread.
Swift
import Foundation @MainActor func updateLabel() { print("Label updated on main thread") } func doWork() async { print("Starting work") await updateLabel() print("Work done") } @main struct Main { static func main() async { await doWork() } }
OutputSuccess
Important Notes
Use await when calling @MainActor functions from outside the main actor.
@MainActor helps prevent crashes caused by updating UI from background threads.
Marking a whole class with @MainActor means all its code runs on the main thread automatically.
Summary
@MainActor ensures code runs on the main thread for UI safety.
Use it on functions, properties, or classes that interact with the UI.
Call @MainActor code with await from other threads.