Proposal for shorthand "if let" syntax in Swift

Originator:will
Number:rdar://19590215 Date Originated:24-Jan-2015
Status:Open Resolved:
Product:Developer Tools Product Version:
Classification: Reproducible:
 
Swift’s optionals are a great idea. They eliminate a whole class of common programming errors. But the `if let` syntax can be a bit verbose at times. This is a proposal to add a simpler, clearer, shorthand syntax for optional unwrapping (to *complement* the existing syntax, not replace it).

Here is the basic `if let` syntax for using an optional:

if let anotherName = perfectlyGoodName
{
  // use 'anotherName'
}

The first problem to notice is that you have to name the unwrapped variable. Naming things is hard, so when you already have a perfectly good name for the variable, who wants to come up with another one?

The solution is simple, and already supported: reuse the same name, shadowing the original:

if let perfectlyGoodName = perfectlyGoodName
{
  // use 'perfectlyGoodName'
}

If this is to become convention, and it looks like it will, then it makes sense to have a shorthand syntax to avoid the redundant repetition. Here’s my first proposal:

if let perfectlyGoodName
{
  // use 'perfectlyGoodName'
}

It’s reminiscent of the way null checks are done in many languages, including Objective-C, so it feels natural and looks cleaner.

But there is another problem with `if let`:

if let a = a
{
  if let b = b
  {
    if let c = c
    {
      // do something which requires a, b, and c to be non-optional
    }
  }
}

When you have multiple optionals that need unwrapping together, you can quickly find yourself navigating a deep hierarchy of nested `if let` blocks. It’s ugly, verbose, and obfuscates the intent of the code.

My second proposal is a shorthand syntax for safely unwrapping multiple optionals simultaneously:

if let a = a, b = b, c = c
{
  // do something which requires a, b, and c to be non-optional
}

The `if let` block is entered only if *all* of the optionals a, b, and c are non-nil. This avoids the multiple nested blocks and makes the code easier to read, and clearer in intent.

And, of course, it works even better with the shorthand name shadowing from above:

if let a, b, c
{
  // do something which requires a, b, and c to be non-optional
}

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!