Blog Article

The Nil-Coalescing ?? and Ternary Conditional :? Operators in Swift


Aasif Khan
By Aasif Khan | Last Updated on December 31st, 2022 9:08 pm | 5-min read

In this tutorial, we’re going to discuss how you can use the nil-coalescing operator and the ternary conditional operator in Swift. They’re both interesting bits of syntactic sugar, and they can help you write more concise, readable code. And that’s a good thing! Here’s what we’ll get into:

  • What operators and operands are
  • How to use the nil-coalescing operator
  • How you can use the ternary conditional operator
  • Real-life examples and tips and tricks for both

What’s an Operator?

Let’s begin by discussing what an operator is, before diving into the nil-coalescing and ternary conditional operators. Here’s what’s what: An operator is a special symbol or phrase that you use to check, change, or combine values. In short, we can use the addition operator + to add two numbers to each other with the expression 4 + 2. In Swift, we can then assign the result of that expression to a constant, such as with let number = 4 + 2. Just as in mathematics! Swift has a great number of operators, including +, -, /, +=, == and also logical operators like &&, || and !. We can also use more complex operators like a..b and a...b for ranges. An operator always uses so-called operands. Operands are the symbols that an operator operates on. If you think of an operator as a function, the operands are the inputs for that function. Check this out: let number = 4 + 2 In the above code, we’re working with two different operators:
  1. The addition operator + adds 4 to 2. The numbers 4 and 2 are operands. We can say that the + operator has two operands, in the format a + b.

  2. The assignment operator = assigns the value of the expression 4 + 2 to the constant number. The constant number and the expression 4 + 2 are operands. We can say that the = operator has two operands, in the format a = b.
In Swift, we have 3 types of operators:
  1. Unary operators have one operand, such as the minus sign operator -a, as in -3. Unary operators can be prefix (before), such as -a, and postfix (after), such as a!.

  2. Binary operators have two operands, such as the addition operator a + b. They’re always infix, because you put the operator between two operands.

  3. Ternary operators have three operands. Swift only has one ternary operator: the ternary conditional operator a ? b : c.
Alright, now that we know a thing or two about operators, let’s move on to the nil-coalescing operator and the ternary conditional operator!

The Nil-Coalescing Operator “??”

The nil-coalescing operator a ?? b unwraps an optional a if it contains a value, or returns a default value b if it’s nil. Differently said, you use the nil-coalescing operator to assign a default value b if a is nil. Based on what we know about operators, we can assert that the nil-coalescing operator a ?? b is an infix binary operator. Here’s an example: let favoriteFood:String? = nil let whatsForDinner = favoriteFood ?? "Fish and chips" print(whatsForDinner) In the above code, you’re getting your favorite for dinner – unless you have no favorite, then you’re getting fish and chips… Feel free to change the value for favoriteFood to a string instead of nil, and see how the output for whatsForDinner changes. In the example, "Fish and chips" is assigned to whatsForDinner if favouriteFood is nil. If it’s not nil, the value of favoriteFood is unwrapped assigned to whatsForDinner. You could say that "Fish and chips" is a default value in case favoriteFood is nil. So, what do you use the nil-coalescing operator for? It’s useful in a few scenarios:
  • When you need a default value, and don’t care much about the optional itself. Take for example a numeric form input field. If it’s not filled in, you don’t need the nil value, so you want to set it to a default of 0 instead. Something like let age = ageInputField?.text ?? 0.
  • When you want to print an optional value with print(), but you don’t want the Optional() debug output. So, instead you write print("Saving object with ID = \(object.id ?? "")") for debugging purposes. If object.id is nil, it’ll print . If it’s not, it’ll print the ID without Optional().
Coalescing means “to come together to one form or mass,” so you could say that the ?? operator merges an optional value with a default value to “come together” as a non-optional value. (I still think nil-splattering operator would have been a more awesome name…)

The Ternary Conditional Operator “?:”

The ternary conditional operator a ? b : c is a special operator that has three parts. It’s a shortcut to evaluate an expression a, and to choose b if a evaluates to true, or c if a evaluates to false. It’s a shorthand for a conditional with if-else, like this: if condition { value_A } else { value_B } If the above condition evaluates to true, the value_A is assigned. If the condition evaluates to false, the value_B is assigned. The ternary conditional operator chooses a value from two options b and c, based on the boolean value of expression a. Let’s look at an example. let temperature = 20 let text = temperature < 0 ? "It's below zero!" : "It's above zero :-)" print(text) In the above code, we’re evaluating the logical expression temperature < 0. Is the temperature below zero or not? Based on this, we got two options:
  1. temperature < 0 is true, so print "It's below zero!"

  2. temperature < 0 is false, so print "It's above zero :-)"
The above code example is exactly the same as: let temperature = 20 let text = "" if temperature < 0 { text = "It's below zero!" } else { text = "It's above zero :-)" } print(text) It’s clear that the ternary conditional operator, with a ? b : c, is much shorter than the above code. In many cases, you don’t even have to use the temporary value text, i.e. you can write the above code as print(temperature < 0 ? ... : ...). The ternary conditional operator is most useful in scenarios where you have two options of equal “weight”, that you’re choosing based on a simple expression. It’s counter-productive if you try to stuff complex logical expressions into the a ? b : c format – in that case, it’s smarter to use a more verbose if conditional block. The nil-coalescing and ternary conditional operators are related! The nil-coalescing operator a ?? b is shorthand for a != nil ? a! : b, which is a shorthand for if a != nil { a! } else { b }. Awesome!

Further Reading

The nil-coalescing and ternary conditional operators are what’s known as syntatic sugar. They sugar-coat verbose code in more concise code, and make your Swift code more readable. Here’s the gist of what we discussed:
  • Use the nil-coalescing operator a ?? b to assign a default value b in case a is nil, and if a is not nil, unwrap a and return it.
  • Use the ternary conditional operator a ? b : c to choose an option b or c based on the value of logical expression a. It’s a shorthand for if-else conditionals.

Related Articles

Aasif Khan

Head of SEO at Appy Pie