When should I use `@MainActor`?

Generated on 8/21/2024

1 search

To determine when to use @MainActor, consider the following guidance from the WWDC session "Migrate your app to Swift 6":

  1. UI-Related Code: Use @MainActor for code that interacts with the user interface. This ensures that UI updates are performed on the main thread, which is necessary for thread safety in UI frameworks like SwiftUI and UIKit.

  2. Delegate Protocols: If you have a delegate protocol that is expected to be called on the main actor, you can annotate it with @MainActor. This is common for protocols that interact with UI components or need to ensure main-thread execution.

  3. Concurrency Guarantees: When you know that a method or callback will be executed on the main actor, you can use @MainActor to inform the compiler of this guarantee. This can help prevent concurrency issues and ensure that your code runs as expected.

  4. SwiftUI Views: In Swift 6, all types conforming to View are implicitly isolated to the main actor by default. If you were previously marking your views with @MainActor, you can now remove that annotation without changing behavior.

For more detailed information, you can refer to the session Migrate your app to Swift 6 (19:29) where delegate callbacks and concurrency are discussed.