swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.54k stars 10.35k forks source link

[SE-0365] Call to method 'bar' in closure requires explicit use of 'self' to make capture semantics explicit #67466

Open khramtsoff opened 1 year ago

khramtsoff commented 1 year ago

Description According to SE-0365 (Allow implicit self for weak self captures, after self is unwrapped) implemented in Swift 5.8:

Additional closures nested inside the `[weak self]` closure must capture self explicitly in order to use implicit self.

And nested closures allowed to capture [self] and use self implicitly (code sample from SE-0365):

// Also allowed:
couldCauseRetainCycle { [weak self] in
  guard let self else { return }
  foo()

  couldCauseRetainCycle { [self] in
    bar()
  }
}

But this code doesn't compile, with the error Call to method 'bar' in closure requires explicit use of 'self' to make capture semantics explicit

Here is the full version:

class Sample {
    func foo() {}
    func bar() {}

    func couldCauseRetainCycle(action: @escaping () -> ()) {
        action()
    }    

    func test() {
        couldCauseRetainCycle { [weak self] in
            guard let self else { return }
            foo()

            couldCauseRetainCycle { [self] in
                bar() // <-- Compile error: Call to method 'bar' in closure requires explicit use of 'self' to make capture semantics explicit
            }
        }
    }
}

let sample = Sample()
sample.test()

Expected behavior Code should compile

Environment

cc @calda

calda commented 4 months ago

This was fixed in https://github.com/apple/swift/pull/70575 👍🏻