Imbricated sending closures & weak self

Hello Swift community !

Just a question about a small detail. I have the following code that triggers a concurrency warning :

final class Foo: Sendable {
    func bar() {
        Task { [weak self] in
            Task { // --> warning : Passing closure as a 'sending' parameter risks 
// causing data races between code in the current task and concurrent execution of the closure; 
// this is an error in the Swift 6 language mode. 
// Closure captures 'self' which is accessible to code in the current task
                self
            }
        }
    }
}

This gets fixed by repeating [weak self] in the second closure.

I'm curious as to know if this is a small compiler issue ? I'm not fully aware yet of the workings of "sending" keyword so this might be perfectly normal behaviour ^^

Thank you

1 Like

I think the compiler is trying to protect you from the potential for this code to be written:

final class Foo: Sendable {
    func bar() {
        Task { [weak self] in
            Task {
                self?.bar()
            }
            self = nil // potentially mutated on a different actor
        }
    }
}

2 Likes

Oh ! that would make sense ! I didn't even know you could nullify weak references ! very interesting, thanks !

1 Like