The Nil-Coalescing ?? and Ternary Conditional :? Operators in Swift
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
Table of Contents
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:- 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.
- 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.
- 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!.
- Binary operators have two operands, such as the addition operator a + b. They’re always infix, because you put the operator between two operands.
- Ternary operators have three operands. Swift only has one ternary operator: the ternary conditional operator a ? b : c.
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().
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:- temperature < 0 is true, so print "It's below zero!"
- temperature < 0 is false, so print "It's above zero :-)"
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
- How to Train ChatGPT for Business: Boosting Your Customer Support Game
- Yahoo Mail vs. Gmail: Which Should You Choose?
- Best Fotor Alternatives for Designers and Businesses in 2023
- Mimosa Color – Exploring History, Psychology, and Design Applications
- Create a Professional Email Signature: Definition, Tips & Best Practices
- The Ultimate Guide to Understanding eCommerce Website Cost in 2024
- How To Generate More Leads for Your Locksmith Business with Chatbots
- How to Get Buzz Cut Filter on Instagram
- 15 Best Gmail Add-ons and Extensions to Use in 2024
- ChatGPT vs. GPT-3: The Key Differences