@MainActor is a Swift attribute that ensures code runs on the main thread/main actor. It’s used to guarantee UI updates and other main-thread-only operations execute safely.
Key uses:
- Classes/structs that update UI
- Properties/methods that must run on main thread
- Preventing data races in concurrent code
- SwiftUI view models and UI-related code
Example:
@MainActor
class ViewModel: ObservableObject {
@Published var data: String = “”
func updateUI() {
// Always runs on main thread
data = "Updated"
}
}