Let's fix `if let` syntax

I broadly agree with others in the thread saying that if let x { ... } feels like the most 'natural' spelling for this shorthand. I think the let or var introducer is important for communicating that there's a new binding occurring, compared to e.g., the if x? { ... } alternative (and yes, I think var should be supported).

As for "omit[ting] the action," we already have another place where we allow a variable name on its own to be expanded to an initialization of a new variable with the same name:

let closure = { [x] in // implicitly: 'let x = x'
    ...
}

This works even if x refers to e.g., self.x in the outer scope.

In this case we don't even force (or permit) the user to specify let to indicate that there's a new binding occurring. However, I've found the lack of an introducer to be a hinderance for users trying to understand what's really going on in a capture list, and IMO it would be even worse of conditional binding since there's really two things going on at once—checking for nil, and binding a new name.

Overall, if let x { ... } feels like a good (new) balance of brevity and clarity. It maintains the existing 'if let' phraseology that I expect most Swift programmers have come to instinctively understand as "bind if non-optional," and the additional behavior is (IMO) easily explainable. It feels so natural to me that I semi-frequently find myself writing it and getting a syntax error before remembering that it's not already supported!

21 Likes