Swift’s Nil Coalescing Operator AKA the “?? Operator” or “Double Question Mark Operator”

This last week I was introduced to quite a funky little operator in Swift called the Nil Coalescing operator. It is basically a shorthand for the ternary conditional operator when used to test for nil.

For example traditionally in many programming languages you could do something like this to check for nil/null…

stringVar != nil ? stringVar! : "a default string"

Here if the condition is not nil the value of stringVar will be returned otherwise the value “a default string” is returned.

This can be shortened in Swift by using the Nil Coalescing operator.

stringVar ?? "a default string"

This does exactly the same thing, if stringVar is not nil then it is returned, however if it is nil the value “a default string” is returned.

Love it.

Technorati Tags: , , , , , , , , ,

Advertisements

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