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

Agreed that most of the style-related arguments here are pretty subjective. For the default case I think if let foo and if let foo? are both totally reasonable.

I do think if let foo meshes more nicely with other syntax / features adjacent to optional unwrapping. Support for explicit type annotations is one example currently included in the proposal / implementation:

if let foo: Foo { ... }

This falls out completely naturally from the change to the grammar, which is to just make the RHS optional. Disallowing this here would make the grammar a bit more complicated / less generalized.

For consistency with other lets / vars in the language, it seems desirable to support type annotations here unless we have a really compelling reason to disallow them. This was brought up in the pitch thread, as one example.

A future direction mentioned in the proposal is support for optional casting:

if let foo as? Bar { ... }

// as potential future shorthand for 
if let foo = foo as? Bar { ... }

I think both of these syntax extensions are a a bit more unnatural with an additional ? symbol:

if let foo?: Foo { ... }

if let foo? as? Bar { ... }
2 Likes