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:

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…

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…

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:

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

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:

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

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