how do i use @mainactor properly

Asked on 2024-07-30

1 search

To use @MainActor properly in Swift, you can follow these guidelines based on the content from the WWDC session "Migrate your app to Swift 6":

  1. Annotate Methods and Properties: You can annotate methods and properties with @MainActor to ensure they are executed on the main actor. This is particularly useful for UI-related code that must run on the main thread.

    @MainActor
    func updateUI() {
        // UI update code
    }
    
  2. Assume Isolated: If you know a function is always called on the main actor, you can use MainActor.assumeIsolated to inform the compiler without starting a new task. This helps avoid unnecessary context switching and ensures the code runs on the main actor.

    func someFunction() {
        MainActor.assumeIsolated {
            // Code that runs on the main actor
        }
    }
    

    This approach is useful when you are certain about the execution context, such as when dealing with delegate callbacks that are guaranteed to be on the main actor.

  3. Non-Isolated Methods: For methods that do not need to be isolated to the main actor, you can declare them as non-isolated. This is useful for callbacks that do not guarantee the execution context.

    nonisolated func someCallback() {
        // Code that does not need to run on the main actor
    }
    
  4. Compiler Fixes: The Swift compiler can help identify where @MainActor annotations are needed. For example, if you get a compiler error indicating that a method should be on the main actor, you can apply the suggested fix to annotate the method.

    @MainActor
    func someMainActorMethod() {
        // Code that must run on the main actor
    }
    
  5. Protocols and Delegates: Many protocols and delegates, especially those related to UI frameworks like SwiftUI, are annotated with @MainActor. This ensures that their methods are called on the main actor.

    protocol SomeDelegate: @MainActor {
        func didUpdateData()
    }
    

For more detailed information, you can refer to the session Migrate your app to Swift 6 at the timestamp 24:15.