We use MainActor to make sure UI updates happen safely on the main thread. This keeps the app smooth and avoids crashes.
0
0
MainActor for UI work in Swift
Introduction
When updating user interface elements like labels or buttons.
When handling user input that changes the screen.
When performing animations that must run on the main thread.
When calling UI-related code from background tasks.
When you want to avoid threading bugs in your app's UI.
Syntax
Swift
@MainActor func updateUI() { // UI code here }
@MainActor marks a function or class to run on the main thread.
This helps keep UI code safe and responsive.
Examples
This function updates a label's text safely on the main thread.
Swift
@MainActor func refreshLabel() { label.text = "Hello!" }
Marking a method inside a class with
@MainActor ensures it runs on the main thread.Swift
class ViewModel { @MainActor func updateData() { // update UI-related data } }
Marking a whole class with
@MainActor means all its methods run on the main thread.Swift
@MainActor class ViewController { func showAlert() { // show alert on UI } }
Sample Program
This SwiftUI app uses @MainActor on the ViewModel class to ensure UI updates happen on the main thread. When the button is tapped, it calls updateMessage() safely with await.
Swift
import SwiftUI @MainActor class ViewModel: ObservableObject { @Published var message = "" func updateMessage() { message = "Hello from MainActor!" } } struct ContentView: View { @StateObject private var viewModel = ViewModel() var body: some View { VStack { Text(viewModel.message) .padding() Button("Update Message") { Task { await viewModel.updateMessage() } } } } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
OutputSuccess
Important Notes
UI updates must happen on the main thread to avoid crashes or glitches.
@MainActor is a simple way to enforce this in Swift concurrency.
Use await when calling @MainActor async functions from other threads.
Summary
@MainActor ensures UI code runs on the main thread.
Use it to keep your app smooth and safe from threading bugs.
Mark functions, methods, or whole classes that update UI with @MainActor.