Swift 2 Pattern Matching: Unwrapping Multiple Optionals

With Swift 1.2, we got the really nice shorthand syntax for unwrapping multiple optionals in one simple if let statement:

var optional1: String?
var optional2: String?

if let optional1 = optional1, let optional2 = optional2 {
    print("Success")
} else {
    print("Failure")
}

🎉💥🎊 This is AWESOME!!!!!! 🌟💃🎈

However, you might still encounter a situation where you do actually have to handle the different combinations of existing / missing optional values. One such example is if you have a form with a username and password field, and the user doesn’t fill one of them out before hitting submit. In this case, you’d want to show the specific error to the user indicating what exactly is missing. To do that, you can use pattern matching!

BS2 (Before Swift 2)

BS2, your unwrapping multiple optionals using pattern matching code would look like this:

var username: String?
var password: String?

switch (username, password) {
case let (.Some(username), .Some(password)):
    print("Success!")
case let (.Some(username), .None):
    print("Password is missing")
case let (.None, .Some(password)):
    print("Username is missing")
case (.None, .None):
    print("Both username and password are missing")
}

It’s a bit clunky. In fact, I had to google my own blog post on how to do this EVERY TIME I had to do this since Swift came out!

Swift 2

In Swift 2, the syntax is a lot cleaner:

var username: String?
var password: String?

switch (username, password) {
case let (username?, password?):
    print("Success!")
case let (username?, nil):
    print("Password is missing")
case let (nil, password?):
    print("Username is missing")
case (nil, nil):
    print("Both username and password are missing")
}

I was at first frustrated by the use of ? to indicate that the value does exist (especially since I associate it with the idea of optionals, where the value may or may not exist), but I have to admit that this example is very clear to understand. And I definitely like it as a much better alternative to the clunky .Some(username) syntax.

What do you think about this new syntax? Would love to hear from you in the comments!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.