does mainactor attribute guarantee a function is always called on main thread?

Generated on 8/5/2024

1 search

The @MainActor attribute in Swift does not guarantee that a function is always called on the main thread. Instead, it indicates that the function should be executed on the main actor, which is associated with the main thread. However, it is still possible for some part of the code to call this function from a context that is not on the main actor.

To ensure that a function is indeed running on the main actor, you can use the assumeIsolated method, which asserts that the code is already running on the main actor. If the function is called from a context that is not on the main actor, it will trap and stop running, preventing potential race conditions.

For more details, you can refer to the session Migrate your app to Swift 6 (24:15).