How do I use MainActor and @MainActor attributes?

The @MainActor attribute in Swift is used to ensure that certain pieces of code are executed on the main thread, which is crucial for any UI-related updates. When combined with the MainActor type, this ensures that any instance methods or properties within a class or struct are executed on the main queue, which avoids potential race conditions and UI glitches.

Using @MainActor is particularly beneficial when dealing with asynchronous code that updates the user interface, as it guarantees that the updates happen on the main thread, preventing crashes and ensuring a responsive user experience.


@MainActor
class MyViewModel {
    var data: String = ""

    func fetchData() async {
        // Simulate a network call
        await Task.sleep(1 * 1_000_000_000) // 1 second

        // Update the data property on the main actor
        self.data = "Fetched Data"
    }

    func updateUI() {
        // UI update code here
        print("UI updated with data: \(self.data)")
    }
}
    

MainActor Swift @MainActor asynchronous programming UI updates thread safety