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

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 and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts