ConcurrencyMidMCQ
What is `MainActor` and when do you use it?
Test your knowledge:
Explanation & Code
Answer:
@MainActor is a global actor that ensures code runs on the main thread. Use it for UI updates, ViewModels, and any code that must not run off the main thread.
Code Example:
@MainActor
class ProfileViewModel: ObservableObject {
@Published var username: String = ""
@Published var isLoading: Bool = false
func loadProfile() async {
isLoading = true
defer { isLoading = false }
username = try await ProfileService.fetchUsername()
// All assignments happen on main thread automatically
}
}
// Marking just a function (not the whole type)
func updateUI() async {
await MainActor.run {
label.text = "Done"
}
}
Rate your understanding: