Allow implicit self in escaping closures when self is explicitly captured

I'd reiterate that explicit self. does not indicate captured self. If one writes self. out of habit, they never see this warning. Making it an error adds to confusion.


This is probably ok, but I think we should carefully evaluate the tradeoff in the case of value types that store references.

I agree.

Big +1 here. This hole leads to cycles in practice. It would be great to see it closed.


My question is how do we play "strong-weak-dance" with this new feature.

Specifically, if in a class, we write code like:

var x

func someMethod() {
  let block = { [weak self] in
    guard let self = self else { return } // <------- (1)
    print(x)     // <------- (2)

My question is:
Is line (2) valid?
If it is, is self referenced weakly or strongly in line (2)?
If it is referenced weakly, how can compiler know that self should be captured strongly, after line (1) is executed and before line (2) is executed?
Does it mean the existence of line (1) will affect the semantics of line (2)?

Strong +1, but I think we should consider the [weak self] and [unowned self] cases.

class Foo {
    var x: Int

    func bar() {
        let block =  { [weak self] in
            let y = x // Int? ????
            baz(using: self) // allowed? will it error as self is weak?
            guard let self = self else { return } // Is it allowed?
            let y2 = x // Is it allowed?

func baz(using foo: Foo) { ... }

In the current state of the proposal/implementation, only a strong, unowned, or unowned(unsafe) capture of self will enable implicit self (EDIT: which is to say, none of the implicit usages of self in the examples of @CrystDragon or @GLanza would be valid under this proposal as it stands). Allowing more general self rebinding is something that could be interesting to pursue, but there are enough additional questions (e.g. if we are willing to look through the weak storage, what else are we willing to look through? Does it work with if let? What about let self = self!) that I think it makes sense to deal with this idea in a separate proposal. Would be interested to hear others’ input, though!

Terms of Service

Privacy Policy

Cookie Policy