Swift Sugar: Ternary Operators – Optional Extension

In my previous post, I wrote some custom operators to function like the Objective-C version of ? : when checking for nil. It worked great, but custom operators ˘\_(ツ)_/˘.

Another approach occurred to me that takes care of the visual clutter that bothered me about this line:

let dependentParameter = optionalParameter != nil ? valueIfNotNil : valueIfNil

I realized that I could simply write an extension to the Optional class:

extension Optional {
    var isNil: Bool {
        get {
            return self == nil

And this works great:

var thing: String? = "HELLO"
thing.isNil //false

thing = nil
thing.isNil //true

So now the ternary operator looks like this and I am even happier:

let dependentParameter = optionalParameter.isNil ? valueIfNil : valueIfNotNil

Either way, both were worth working through.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s