Sobes.tech
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 @MainActor to ensure execution on the main thread.
  • For asynchronous functions, you can use @MainActor together with async.
  • If you call a function marked with @MainActor from another thread, use await to 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.