This already exists with if let foo = foo
since just plain let foo = foo
is not valid Swift. This hasn't seemed to be a significant problem with people not able to trust what let
and var
mean.
That said, I agree that if let a = b
may not be the optimal syntax for optional binding. Newcomers need to learn that if let
and if var
are not the same as just let
and var
. But as I describe in more detail below, I think if let
would be difficult to move away from at this point.
One drawback is that it doesn't allow the choice between creating an immutable or (much more rare) mutable unwrapped variable that let
and var
provide.
But beyond that, I think introducing a new keyword for this purpose introduces more complexity than it resolves.
If the keyword is only used as a synonym for if let x = x
, then it needs to be mixed and matched with if let
-style bindings when multiple items are bound in a single statement:
if unwrap user, let defaultAddress = user.shippingAddresses.first { }
This is easily a point of confusion to people new to the language, but it would be a natural question for everyone to ask "Why can't I use unwrap
in both cases? Why do I have to use let
sometimes and unwrap
sometimes?"
It wouldn't seem to make much sense to be able to use unwrap
in one case and not the other. To fix this friction, a next step would be to allow unwrap
instead of let
for optional binding:
if unwrap user, unwrap defaultAddress = user.shippingAddresses.first { }
And, on its own, I think that reads well.
But, without a source breaking change, if unwrap
would always need to exist alongside the existing if let
. Some projects will prefer one or the other, essentially creating two dialects of Swift for an incredibly common construct. And to move between codebases, everyone will need to know and understand both syntaxes (and if working on different projects keep track of which project prefers which style).
I think in practice both the "mix and match" style and the "both coexist" style would add a good deal of unwanted complexity over the current state of things and over the proposed solution.