Improvements to optional unwrapping in Swift

Originator:tschmitz
Number:rdar://19234512 Date Originated:12/12/14
Status:Open Resolved:
Product:Developer Tools Product Version:
Classification:Enhancement Reproducible:N/A
 
I think it's worth making some tweaks to how optional unwrapping works, and I have two suggestions. Here's an example of a fairly common scenario:

var a: Int? = 1
var b: Int? = 2
var c: Int? = 3

if let realA = a {
  if let realB = b {
    if let realC = c {
      let sum = realA + realB + realC
      println("Sum: \(sum)")
    }
  }
}

Unwrapping gets pretty cumbersome. The first problem is this deep nesting. Many times you don't really want to do anything if the optional is nil, you just want to handle the case where all of the variables have a value. Why not allow `if-let` to include multiple terms, the way you might with any other `if` statement, like so:

var a: Int? = 1
var b: Int? = 2
var c: Int? = 3

if let realA = a && let realB = b && let realC = c {
  let sum = realA + realB + realC
  println("Sum: \(sum)")
}

Secondly, it's often irritating to come up with another name for the unwrapped variable, and you sometimes even see developers do things like `if let a = a`. In this case, the name `a` represents the unwrapped optional inside the `if` statement. Why not allow the language to do something like this:

var a: Int? = 1
var b: Int? = 2
var c: Int? = 3

// Equal to if let a = a && let b = b && let c = c
if let a && let b && let c {
  let sum = a + b + c
  println("Sum: \(sum)")
}

It keeps the functionality of optionals in place, and adopts some of Swift's conciseness, while making the code less leggy.

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!