How do you quiet warnings about strict swift concurrency when accessing an instance method from a main actor callback that has to capture through a non-main layer

Generated on 7/30/2024

1 search

Tailscan

This post is brought to you by Tailscan, the best devtool for Tailwind CSS.

To quiet warnings about strict Swift concurrency when accessing an instance method from a main actor callback that has to capture through a non-main layer, you can use the @MainActor annotation or the assumeIsolated method. Here are the steps you can follow:

  1. Annotate the Delegate Protocol: If you have control over the delegate protocol, you can annotate it with @MainActor to ensure that all its methods are called on the main actor. This will help the compiler understand the concurrency guarantees.

    @MainActor protocol CaffeineThresholdDelegate {
        func caffeineLevelDidChange()
    }
    
  2. Use assumeIsolated: If you cannot modify the delegate protocol (e.g., it's part of a third-party library), you can use the assumeIsolated method to tell the compiler that the callback is guaranteed to be called on the main actor.

    class MyViewModel: ObservableObject, CaffeineThresholdDelegate {
        @MainActor
        func caffeineLevelDidChange() {
            // This method is guaranteed to be called on the main actor
            assumeIsolated(self) {
                // Your code here
            }
        }
    }
    
  3. Declare the Method Non-Isolated: Another option is to declare the method as non-isolated if you know it will be called on the main actor but the protocol does not guarantee it.

    class MyViewModel: ObservableObject, CaffeineThresholdDelegate {
        nonisolated func caffeineLevelDidChange() {
            Task { @MainActor in
                // Your code here
            }
        }
    }
    

For more detailed information, you can refer to the Migrate your app to Swift 6 session from WWDC 2024, particularly the chapter on "Delegate callbacks and concurrency".

Relevant Sessions