SE-0345: `if let` shorthand for shadowing an existing optional variable

I'm very glad to see this come to review and believe it is an important quality of life improvement. Some form of sugaring for scoped "unwrap this and let me work with it" is a very frequently requested feature (see @chockenberry 's Let's Fix if let Syntax thread from last year, for example), and the source of some not inconsiderable Kotlin envy from developers working with both languages.

But this proposal solves the ergonomics in a way that I believe fits neatly into the existing language, in a way imitating Kotlin's != nil type refinement approach would not. It is simple to explain – you are just eliding the = x in if let x = x – and fits with the many other places in the language where you can elide "obvious" implied ceremony, leaving clear code that feels more lightweight. This simple model of eliding the rhs of the assignment while keeping the let or var also means it will scale neatly to new introducers for shared and mutable borrows.

Here and in the pitch thread, the majority of opposition is regarding shadowing and potential ensuing confusion from shadowing. Many comments here ignore or deny the fact that this shadowing happens today with exactly the common idiom this proposal aims to sugar. Like it or not, shadowing is a reality for Swift, so merely saying "this is bad because it shadows a variable" is insufficient reason to oppose this sugar.

A case against would need to go further such as:

  • if let x is less clear in its shadowing intent than if let x = x; or
  • Sugaring if let x = x encourage this idiom, and this would be bad because it encourages shadowing and shadowing is bad, developers should instead try to write if let y = x to distinguish the wrapped and unwrapped values.

Neither of these seem credible to me. I just do not believe anyone would find the absence of the = x on the rhs suddenly means that the shadowing of the unwrapped value is any less clear. One reason why this proposal is better than Kotlin's approach is that the let remains. In fact the dropping of ceremony (especially with long variable names) might make it more clear. As to encouraging people to find a different name for the unwrapped value... everyone knows naming is the hardest problem in computer science, so that just seems cruel (see the "let's fix if let" thread for a longer less flippant reason why forcing finding of new names harms readability :).

35 Likes