Summary
For a few major Swift versions the following code is allowed to work with weakly captuered self
:
guard let `self` = self else { /* … */ }
// proceed with non-optional self
It's a wide-spread pattern today. The consenses from past discussions is that this has been a compiler bug. Ways to fix it have been suggested.
Past Discussions
There was a SE discussion about this and an older discussion dated all the way back to 2015. There's at least one Twitter conversation I can find.
Motivation
At various times it was pointed out this ought not to be an Swift Evolution topic. But the source-compatibility story for Swift has changed over time. As weakly captured self is pervasive in Swift code, this is an worthy topic to formally settle (unclear in what way) as part of the language.
Personally, I work on codebases in which the pattern mentioned in Summary is widely adopted. Recently, my team started to re-evaluate the decision of endorsing this pattern for a very specific reason: an lldb bug in which the rebound self
makes lldb extremly unhappy. It's reasonable to say that whether/how this lldb bug will be fix is tied to the future of this langauge construct. Therefore I'd like a reading on the barometer in the community.
Options For Change
1. Allow self
Shadowing
Enhance the compiler such that guard let self = self else { /* … */ }
works. If I'm not mistaken, this is the option many from the compiler team suggested in the past.
Pros: it appears to be "the right thing" from a design point-of-view; there's a clear migration path for the existing "bug".
Con: we'll have to do an migration.
2. Make the bug a feature
The pattern mentioned in the Summary section is widely used. In one of my team's projects, there are 50 occurances in a 48k LOC Swift-only module, not counting blanks and comments. A quick search for the exact phrase on Twitter reveals that it's been shared as a "pro tip" over the years it has existed. So it's not unreasonable to have a SE proposal to make this syntax an official part of the language.
Pro: good source compatibility.
Cons: murkier language design. self
becomes even more special. The role of backticks becomes inconsistent.
3. No support for weak self rebinding
We can simply migrate users away from using this pattern and decide whether/when/how to improve this pattern later. Swift users can use other identifiers for weak self rebinding.
Pros: gives a clear signal to early adopters in the community to move away from exploiting the compiler bug; clear migration path; probably simple to implement.
Cons: we'll have to do an migration; some may think this creates an inconvenience.
Discuss!
Please read up on past discussions (they are short, relatively speaking) and share your thoughts.