Swift: Unwrapping Multiple Optionals

Believe it or not, but I’m still getting used to optionals in Swift. Just when I thought I was getting the hang of it, I came across a new use-case where I found it hard to figure out how to proceed. Here is a class similar to the one I was creating, with multiple optional values:

Swift Multiple Optionals

As you can see, the description that was printed out was definitely NOT what I had in mind! It’s weird that XCode does not give an error or warning to unwrap an optional – it just goes ahead and prints out the wrong thing. I’ll make sure to file a radar on this!

In retrospect, unwrapping the name and favoriteActivity optionals makes sense, so I tried this…

Swift Optionals Unwrapping Error

Again, maybe in retrospect this makes sense, but I was surprised that I couldn’t unwrap both optionals in one if statement.

After searching around for a bit, I found that a way to do this is through Swift’s pattern matching…

Minion Description

This may not be super intuitive, but it’s definitely powerful once I get used to it! For example, you can now pattern match for any use case of nil:

Swift Pattern Matching

Now, that’s beautiful! The resulting descriptions for my Minion class are now as expected:

Swift Pattern Matching Description

I haven’t explored pattern matching in Swift much before this, but I’m now suddenly very excited about it’s possibilities! What do you think?

UPDATE@tammofreese pointed out that I should be using .None in my switch statement instead of nil. Here is his amazing explanation from the comments below:

Tommo Freese Comment

The better solution with the .None in the swift statements looks like this:

Screen Shot 2014-08-02 at 3.13.24 PM

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