Without dissuading this effort—indeed, I'd love if this is improved—I'll note some cases where if let foo = foo
has effects beyond simply making foo
non-optional:
-
foo
is reallyself.foo
; if we're in a mutating method or a class method,self.foo
could change within the body of theif
whilefoo
stays the same -
foo
is a global variable (or type-level variable in a type-level method); the same could happen -
foo
is a capturedvar
; the same could happen iffoo
is also captured in another closure. (This one's pretty rare.) -
foo
is a localvar
. Withif let
, this shadows the localfoo
, making it unassignable within the body.
One answer is to say that the shorthand will not allow any of these; it will only work when foo
is already immutable (i.e. declared with let
or as a function parameter). I think that's perfectly valid, at least for the first version of a proposal, since it's possible to open up later. I just want to make sure it gets mentioned.