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":
-
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. -
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. -
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. -
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.
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.
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.
A Swift Tour: Explore Swift’s features and design
Learn the essential features and design philosophy of the Swift programming language. We’ll explore how to model data, handle errors, use protocols, write concurrent code, and more while building up a Swift package that has a library, an HTTP server, and a command line client. Whether you’re just beginning your Swift journey or have been with us from the start, this talk will help you get the most out of the language.