Junior — Middle
Milliseid juhiseid tuleb järgida MainActor kasutamisel?
sobes.tech AI
Vastus AI-lt
@MainActor in Swift is used to indicate that the code should run on the main thread, which is important for updating the UI and other operations that require the main thread. Main 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
}
This way, @MainActor helps prevent errors related to updating the UI from a non-main thread.