Let’s all meet on the Playground!

One of the things I absolutely LOVE about Swift is the Playgrounds! A good, easy to use REPL mode (which is part of Swift Playgrounds is) is especially helpful when learning a new language. If I’m ever in doubt or just wondering how Swift is going to handle a certain situation then I can just hop onto the Playground and try it out.

Today I was wonder exactly how Swift handles the equality of Optional (nil) values. Optionals are still one of those areas with Swift (besides Protocols and Generics) that I’m still a little hazy on. My specific question was this: “Do I have to unwrap the optionals to test their equality or can I just test them as is?”

So I just hopped onto Xcode and tried it out in the Playground with the following:

import Foundation

func foo(a: String?, b: String?) {
    if a == b { print("a (\(a)) and b (\(b)) are equal.") }
    else { print("a (\(a)) and b (\(b)) are NOT equal.") }
}


foo(a: "Galen", b: "Galen")
foo(a: "Galen", b: "Rhodes")
foo(a: nil, b: "Galen")
foo(a: "Galen", b: nil)
foo(a: nil, b: nil)

The results were just as I had hoped they would be.

a (Optional("Galen")) and b (Optional("Galen")) are equal.
a (Optional("Galen")) and b (Optional("Rhodes")) are NOT equal.
a (nil) and b (Optional("Galen")) are NOT equal.
a (Optional("Galen")) and b (nil) are NOT equal.
a (nil) and b (nil) are equal.

This means that I can just directly compare to variables together without having to worry if they are nil (unless I want to worry about it) without having to unwrap them first.

A quick change to the code and I was able to test what would happen if only one of the variables was an Optional and the other wasn’t.

Just as I had hoped. I still don’t have to unwrap the Optional! Yay!

Leave a Reply