I have a function in a class that is marked with @MainActor. Is there a way to make mark this function so that it is not run on the main actor?

Generated on 7/31/2024

1 search

To mark a function in a class that is annotated with @MainActor so that it is not run on the main actor, you can declare the method as nonisolated. This means that despite the class being isolated to the main actor, this specific method will not be isolated to the main actor.

Here is an example of how you can do this:

@MainActor
class MyClass {
    func someMainActorFunction() {
        // This function runs on the main actor
    }

    nonisolated func someNonIsolatedFunction() {
        // This function does not run on the main actor
    }
}

This approach is useful for callbacks or methods that intentionally make no promises about where they are called from.

For more details, you can refer to the session Migrate your app to Swift 6 at the timestamp 17:12.