Swift Ternary Conditional Operator

In this article, you will learn to use conditional or ternary operator to alter control flow of the program.

The ternary conditional operator "? :" is a shorthand for if-else statement.

The syntax for ternary conditional operator is:

condition ? value1 : value2

How ternary conditional operator works?

Here's how this works

  • If the condition is true, it returns value1.
  • If the condition is false, it returns value2.

The above equivalent code using if - else is:

if condition {
	value1
} else {
	value2
}

Why use ternary Conditional Operator?

You may be wondering why should we use conditional operator if it does the same job as if-else statement. The main purpose of using it is to make code shorter and more readable.

For simple conditions, you can evaluate it in a single line with less code than if-else.


Example 1: Simple example using ternary conditional operator

print(true && false ? "The condition is true": "The condition is false")

The above equivalent code using if - else is:

if true && false {
	print("The condition is true")
} else {
	print("The condition is false")
}

When you run the above program, the output will be:

The condition is false

In the above program, the expression true && false evaluates to false, therefore the statement returns the string The condition is false and print statement outputs the string in the console.

If you change the expression as true || false the statement evaluates to true and returns the string The condition is true and print statementoutputs the string in the console.


Things to remember

Ternary conditional operator can also be used as an alternative of if-else-if statement.

With the use of ternary conditional operator you can replace multiple lines of if-else-if code with a single line.

However, it may not be a good idea.

Example 2: Nested if else using ternary conditional operator

if true && false {
	print("Result is \(true && false)")
} else if true || false {
	print("Result is \(true || false)")
} else if false || false {
	print("Result is \(false || false)")
} else {
	print("Default else statement")
}

The above equivalent code using ternary conditional operator is:

print(true && false ? "Result is \(true && false)" : true || false ? "Result is \(true || false)" : false || false ? "Result is \(false || false)" : "The condition is unknown")

When you run the above programs, both output will be:

Result is true

In the above programs, although the statements of if-else-if is replaced with single line by the use of conditional operator. The expression used in ternary conditional operator is really hard to understand.

So, just stick to the use of ternary conditional operator as an alternative of if-else statement only.