Sobes.tech
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 @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
}

Thus, @MainActor helps avoid errors related to updating the UI from a non-main thread.