When writing a framework, does it makes sense to mark everything with a MainActor annotation?

Generated on 8/3/2024

1 search

When writing a framework, it does not necessarily make sense to mark everything with a MainActor annotation. The context from the session "Migrate your app to Swift 6" at WWDC 2024 provides several insights:

  1. Selective Annotation: Many delegates and protocols, especially those related to UI frameworks like SwiftUI views, are already annotated with MainActor in the latest SDKs. This means you might not need to add as many MainActor annotations as before (Migrate your app to Swift 6).

  2. Assume Isolated: If you know a method is always called on the main actor, you can use MainActor.assumeIsolated to inform the compiler without starting a new task. This is useful for methods where you have verified the concurrency guarantees (Migrate your app to Swift 6).

  3. Non-Isolated Methods: For callbacks that do not guarantee they will be on the main actor, you can declare methods as non-isolated. This approach is suitable for backend operations or when the concurrency context is not fixed (Migrate your app to Swift 6).

  4. Framework-Specific Guarantees: Some frameworks, like WatchKit, provide guarantees that certain callbacks will always be on the main actor. In such cases, marking everything with MainActor might be redundant (Migrate your app to Swift 6).

In summary, while MainActor annotations are useful, they should be applied judiciously based on the specific concurrency guarantees and requirements of your framework. Over-annotating can lead to unnecessary complexity and potential performance issues.