Introduction
Optional binding is one of the most popular ways to unwrap an optional value. Moreover, when the optional is in the current scope, like self, it's standard practice to initialize the bound constant with the same name. Consider the following very common scenario occurring inside closures that weakly capture self:
guard let self = self else {
return
}
Proposed solution
Because this approach is so popular I propose to introduce the option to omit the assignment and implicitly use the same name:
guard let self else {
return
}
This behavior would obviously extend to other control flow statements:
if let error {
preconditionFailure(error.localizedDescription)
}
Motivation
This would enforce good practice by default. Using a different name, like strongSelf
adds unnecessary complexity in my opinion. In the spirit of progressive disclosure, customizing the name of the bound constant could be considered an advanced feature that novice language users don't have to know about when getting started.
Inspiration
Capture lists follow the same implicit naming pattern:
[weak self = self]
Personally, because I encounter the weak self dance so frequently, this change would make code simpler to read and reason about. What do you think?