Junior — Middle
What instructions should be given when using MainActor?
sobes.tech AI
Answer from AI
@MainActor in Swift is used to indicate that the code should be executed on the main thread, which is important for updating the UI and other operations requiring the main thread. Key guidelines when using MainActor:
- Annotate classes, structures, functions, or properties with
@MainActorto ensure execution on the main thread. - For asynchronous functions, you can use
@MainActortogether withasync. - If you call a function marked with
@MainActorfrom another thread, useawaitto switch to the main thread.
Example:
@MainActor
class ViewModel {
var title: String = ""
func updateTitle() {
title = "Updated"
}
}
func someBackgroundTask() async {
let vm = ViewModel()
await vm.updateTitle() // switch to main thread
}
Thus, @MainActor helps avoid errors related to updating the UI from a non-main thread.