iosswiftswiftuiasync-awaitactor

How to use an @State property from a Sendable Closure in SwiftUI?


Here, hasComplexWave is a Boolean @State on a SwiftUI View. Here’s the code that uses it:

view.visualEffect { [hasComplexWave] content, proxy in
    content.distortionEffect(
        ShaderLibrary.complexWave(
            .float(startDate.timeIntervalSinceNow),
            .float2(proxy.size),
            .float(0.5),
            .float(8),
            .float(10)
        ),
        maxSampleOffset: CGSize(width: 100, height: 100),
        isEnabled: hasComplexWave
    )
}

The problem is, this gives me a warning in swift 5 and an error in swift 6, as follows:

Main actor-isolated property 'hasComplexWave' can not be referenced from a Sendable closure; this is an error in the Swift 6 language mode

What is the very best way to fix this error?


Solution

  • You can add a “capture list” to the closure to avoid referencing the actor-isolated property in the closure.

    Thus, replace …

    view.visualEffect { content, proxy in … }
    

    … with:

    view.visualEffect { [hasComplexWave] content, proxy in … }
    

    See Capture Lists and Capturing Values from The Swift Programming Language.