what can be marked as @MainActor?

Generated on 8/6/2024

1 search

In Swift, you can mark various elements with the @MainActor attribute to ensure they are executed on the main actor, which is typically associated with the main thread. Here are some examples of what can be marked as @MainActor:

  1. Methods: You can mark methods to ensure they run on the main actor. This is useful for UI updates or other tasks that must be performed on the main thread.

    • Example: @MainActor func updateUI() { ... }
  2. Protocols: Protocols can be annotated with @MainActor to ensure that all conforming types and their methods are executed on the main actor.

    • Example: @MainActor protocol MyProtocol { func doSomething() }
  3. Classes and Structs: Entire classes or structs can be marked with @MainActor to ensure all their methods and properties are accessed on the main actor.

    • Example: @MainActor class MyViewController: UIViewController { ... }
  4. Global Instances and Functions: You can also mark global instances and functions to ensure they are accessed on the main actor.

    • Example: @MainActor let sharedInstance = MySingleton()

In the context of the WWDC sessions, the @MainActor attribute is particularly relevant for SwiftUI views and delegate protocols. For instance, the SwiftUI.View protocol is implicitly isolated to the main actor by default in Swift 6, so you no longer need to explicitly mark your views with @MainActor (What’s new in SwiftUI).

Additionally, when dealing with delegate callbacks, it's important to understand the concurrency guarantees. Many UI frameworks guarantee that callbacks will be on the main thread, and you can use @MainActor to enforce this (Migrate your app to Swift 6).

For more detailed information, you can refer to the session Migrate your app to Swift 6.