Improving Swift Optional Unwrapping

Developing in Swift can often mean dealing with multiple levels of optional unwrapping. It’s messy and it’s annoying. Colin Eberhardt’s post got me thinking about better ways to deal with this, and he has some suggestions that work without modifying the language.

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. I’ve filed a Radar that you can dupe if you agree.