[swift-evolution] Obsoleting `if let`
jgroff at apple.com
Wed Feb 3 17:50:08 CST 2016
> On Feb 3, 2016, at 3:36 PM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
> This is a continuation of and alternative proposal to "The bind thread", which seems to have petered out without consensus.
> Currently there are three forms of `if` statement (and `guard` and `while`, but for simplicity I'll just say `if` throughout this discussion):
> if booleanCondition
> if let name = optionalCondition
> if case pattern = expression
> The boolean condition form is fine, but there are flaws in the other two. `if let` is unprincipled and doesn't really say what it does; `if case` is bulky and rarely used.*
> One very interesting thing about `if case`, too, is that it can actually do optional unwrapping:
> if case let name? = optionalCondition
> This avoids the problems with `if let`—it's principled (it comes from a larger language feature) and it explicitly says it's handling optionality—but it still runs up against `if case`'s rarity and wordiness.
> So what I suggest is that we drop the `if let` form entirely and then drop the `case` keyword from `if case`. Pattern-matching conditions can still be distinguished from boolean conditions because boolean conditions can't contain an `=` operator. This, there would now only be two forms of if:
> if booleanCondition
> if pattern = expression
> And the current `if let` is handled elegantly and clearly by existing pattern-matching shorthand, with only one additional character needed:
> if let name? = optionalCondition
This was in fact our original design for the pattern-matching-in-conditions feature. We went with the alternative 'if case' design for a couple of reasons:
- As you noted, for loops are weird. `for case` makes it clearer that filtering is happening, whereas something like 'for x as T in sequence' is more ambiguous.
- The way 'if let x = y' ends up a no-op is a big pitfall
- Optional unwrapping is by far the most common use case for these conditions, and we got a huge amount of pushback from our users in Apple complaining about the extra syntax all over their code. 'if let' for better or worse has also become one of Swift's trademarks.
I like this unification as an ivory-tower language designer, but user experience had to win out.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution