The Ternary Operator in Swift

swift Jul 21, 2022
The Ternary Operator in Swift

In Swift, we often use if-else statements to perform some conditional operations. In some cases, we can use ternary operator instead of if-else to write more readable code. To understand how the ternary operator works, let's examine its syntax.

In order to understand ternary operators, we assume you are familiar with if-else statements.

Ternary Operator Syntax:

condition ? expression1 : expression2

In syntax,

If condition == true, expression1 will execute.

If condition == false, expression2 will execute.

Note: Here you can see there are 3 operands (condition, exp1, exp2). Therefore, the term ternary operator.

How to use it?

Here, we will check if a given number is even or odd. As a first step, we will use an if-else statement and then the ternary operator.

Using if-else statement:

let number = 10
var result: String

if number % 2 == 0 {
    result = "even number"
} else {
    result = "odd number"
}

// result = even number

Using ternary operator:

let number = 10
var result: String
result = (number % 2 == 0) ? "even number" : "odd number"

// result = even number

You can see that ternary operator makes it easy to check if the number is even or odd, only in a single line of code.

Nested Ternary Operator

Just like how we deal with multiple conditions using if, else-if, else statements, we can deal with same conditions using ternary operator too by writing nested ternary operator cases. For example:

let number = 10
let result = (number == 0) ? "zero" : ((number > 0) ? "positive number" : "negative number")

// result = positive number
Note: Using nested ternary operators will sometimes make your code difficult to read. In other words, you can completely replace the if-else statement that is true, but you should always choose readability over brevity.

Ternary operator with optional variable

Yes, you can use ternary operator to unwrap an optional variable.

var name: String? = "Johny"
let nameValue = name != nil ? name! : "no_name"

// nameValue = "Johny"

But we have another operator nil coalescing to check optional variable to unwrap value like below:

var name: String?
let nameValue = name ?? "no_name"

// nameValue = "no_name"

This is recommended way to unwrap value from optional variable.

Note: There is another operator called nil coalescing in Swift, which is similar to the ternary operator by syntax. As you know, ternary operator uses a single question mark (?), and nil coalescing uses a double (??). Make sure you don't confuse the two. They are both used for different reasons.

Congratulations! Today you learned about the ternary operator in Swift and the best practices to use them in your codebase to write more readable code. We recommended you to read more articles like Conditional Statements in Swift and Generate Random Number.

Signup now to get notified about our
FREE iOS Workshops!