`if let` shorthand

I'm not making any statement about whether the if var x = x syntax is confusing. I'm suggesting that a new if var x { syntax could be. I'm not suggesting that we remove if var x = or guard var x =!

More generally, I suggest going back to basics on "why do we sugar things" and ask whether the rationale applies to "if var".

The goal of Swift language design isn't to minimize number of characters in code, it is to find a balance between "expressivity", and "readability". Readability isn't just "what does this line of code do" it is a deeper "what is the lifecycle of maintaining and evolving a codebase, particularly when it is worked on by multiple people, or the project spans years of development".

We could sugar lots and lots of things - there is ample grammatical space to introduce new things into the language - but each new thing we introduce is something that Swift programmers will be expected to know/learn when they encounter them in a code base. Further, we have to consider what the implications are for the larger maintainability of the code base.

In the case of if var x {, my understanding is that if var x = x { is FAR less common than the corresponding if let x = x { pattern, because it is extremely uncommon to make a mutable copy of something inside of an unwrap. Given that, the benefit of sugaring this is very low.

At the same time, the cost of confusion is potentially very high. Both because some people will expect that this has something akin to an "inout" binding to the underlying value (when the original optional value is mutable). This confusion isn't possible with the 'if let' pattern because it is an immutable binding.

Am I wrong that if var x = x { is uncommon in swift code today?

-Chris

17 Likes