Swift Nil Coalescing (??) And Ternary Conditional (?:) Operator Explained

By Eddy Chung

Operators are symbols that check, change or combine values.

In this article, we’ll go over the two most confusing Swift operators, the double question mark (??) nil-coalescing operator and the ternary condition operator (= ? a : b).

Nil-Coalescing Operator, Double Question Mark

The nil coalescing operator looks like double question marks ??. It’s basically short hand for this block of code:

if userInput != nil {
    return userInput!
} else {
    return "default"

So we can use the nil coalescing operating to make this function into one line and assign the returned value:

let x = userInput ?? "default"

This means x will get the value of userInput only if it is not nil, otherwise it will get the value "default". This operator is used often in Swift to work with optionals without having to write if statements all the time.

Ternary Conditional Operator, One Line If Statement

The ternary conditional operator is a short hand technique used to simplify this block of code:

if condition {
    return "a"
} else {
    return "b"

With the ternary conditional operator we can do this:

let x = condition ? "a" : "b"

This above code says to assign “a” to x if condition is true, otherwise assign “b”.

Super slick right? Ternary conditional operators are like one line if statements.

If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts