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:
-
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 manyMainActor
annotations as before (Migrate your app to Swift 6). -
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). -
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).
-
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.

Migrate your app to Swift 6
Experience Swift 6 migration in action as we update an existing sample app. Learn how to migrate incrementally, module by module, and how the compiler helps you identify code that’s at risk of data races. Discover different techniques for ensuring clear isolation boundaries and eliminating concurrent access to shared mutable state.

What’s new in SwiftUI
Learn how you can use SwiftUI to build great apps for any Apple platform. Explore a fresh new look and feel for tabs and documents on iPadOS. Improve your window management with new windowing APIs, and gain more control over immersive spaces and volumes in your visionOS apps. We’ll also take you through other exciting refinements that help you make expressive charts, customize and layout text, and so much more.