MainActor annotation in Swift 5

Swift 5 introduces a new feature called “actors” which makes it easier to write concurrent and asynchronous code. One of the key features of actors is the ability to ensure that all access to the actor’s state is serialized and performed on the actor’s thread. The @MainActor annotation is a new addition to Swift 5 that helps ensure that certain code is always executed on the main thread.

The @MainActor annotation can be applied to properties, methods, and even entire classes or structs. When you apply the annotation, you’re telling the Swift compiler that the code inside that property, method, or type must always be executed on the main thread. This is useful when you’re dealing with UI code or any other code that needs to be executed on the main thread for thread-safety reasons.

Here’s an example of how you can use the @MainActor annotation to ensure that a property is always accessed on the main thread:

class MyViewController: UIViewController {
    @MainActor private var myProperty = 0
    
    func updateProperty() {
        DispatchQueue.global().async {
            // This code is executed on a background thread
            self.myProperty = 1
        }
        
        DispatchQueue.main.async {
            // This code is executed on the main thread
            print(self.myProperty) // Always executed on the main thread
        }
    }
}

In this example, we’re using the @MainActor annotation to ensure that myProperty is always accessed on the main thread. Even though we’re modifying the property on a background thread, we can safely read it on the main thread because the @MainActor annotation guarantees that it will always be accessed on the main thread.

The @MainActor annotation is a simple but powerful addition to Swift 5 that makes it easier to write thread-safe code. If you’re working with UI code or any other code that needs to be executed on the main thread, the @MainActor annotation is definitely worth considering.

A pat on the back !!