English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Ternary Operator

In this article, you will learn to change the specific flow of the program using conditional or ternary operators.

The ternary operator "? :" isif-else statementabbreviation.

The syntax of the ternary operator is:

condition ? value1 : value2

The ternary operator works?

This is how

  • If condition is true, return value1.

  • If condition is false, return value2.

The equivalent code above uses if-else is:

if condition {
	value1
} else {
	value2
}

Why use the ternary operator?

You may wonder why use the ternary operator if it performs the same as if-to do the same work as the else statement. The main purpose of using it is to make the code shorter and more readable.

For simple cases, you can use the ternary operator instead of if-else calculates less code in one line.

Example1: A simple example of using the ternary operator

print(true && false ? "Condition is true" : "Condition is false")

The equivalent code above uses if-else is:

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

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

Condition is false

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

If you change the expression to true || false, the statement evaluates to true and returns the stringCondition is true, the print statement outputs a string to the console.

Notes

The ternary operator can also be used as if-else-with the alternative to the if statement.

By using the ternary operator, you can replace multiple lines of if-else-if code.

But sometimes, this may not be a good method.

Example2: Use nested if with the ternary operator-else

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 equivalent code for the above 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 program, the two outputs will be:

Result is true

In the above program, although the if statement is used with the ternary conditional operator-else-Replace the if statement with a single line. However, the expressions used in the ternary conditional operator are indeed difficult to understand.

Therefore, it is necessary to use the ternary conditional operator according to the actual situation.