Addressing a warning about capturing a non-sendable type in a sendable closure

I am trying to prepare my code for Swift 6 and have enabled strict concurrency settings.

In there I get the warning:

Capture of 'decisionHandler' with non-sendable type '(WKNavigationActionPolicy) -> Void' in a `@Sendable` closure

Which I would like to address. The error occurs on line 32, where the decisionhandler is called.

Here is the simplified (incomplete) code that shows the problem.

// This is incomplete code. It just shows the barebone details
// to show where the error happens.
class WebView: WKWebView {
    init(headers: [String: String]) {
        self.headers = headers
        super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0), configuration: WKWebViewConfiguration())
    }
}

extension WebView: WKNavigationDelegate {
    private func customHeadersPresent(navigationAction: WKNavigationAction) -> Bool {
        for (key, _) in headers where navigationAction.request.value(forHTTPHeaderField: key) == nil {
            return false
        }
        return true
    }

    nonisolated func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationAction: WKNavigationAction,
        decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
    ) {
        // This needs to happen in the MainActor because the method customHeadersPresent
        // when called directly will give the error:
        //   Call to main actor-isolated instance method 'customHeadersPresent(navigationAction:)' 
        //   in a synchronous nonisolated context
        Task { @MainActor in
            if navigationAction.request.httpMethod != "GET" || customHeadersPresent(navigationAction: navigationAction) {
                // because this is running in the main actor I get the warning:
                //  Capture of 'decisionHandler' with non-sendable type 
                //  '(WKNavigationActionPolicy) -> Void' in a `@Sendable` closure
                return decisionHandler (.cancel)
            }
        }
    }

}

Any advice on how to address this warning would be appreciated.

Can customHeadersPresent() be made nonisolated?

No, it can't. If I do that it cannot access the headers variable.

Why not using async version of delegate interface?. Do you have a reason to use completion based objective-c style rather than async version?

1 Like

I was not aware there is an async interface. I will have to investigate this. Nothing against it.

As it turns out this solves the issue. Thanks for the support.

1 Like