In this tutorial you will learn about the Swift Ternary Operator and its application with practical example.
Swift Ternary Operator
In swift, ternary (?:) operator is a shorthand method for if else statement, which allows to express if else statement in single line. It is also known as conditional operator.
Syntax:-
1 |
condition ? resutl1 : result2 |
Here, condition is a Boolean expression that results in either True or False, if it results in True then result1 will be returned, if it results in False then result2 will be returned.
Example:-
1 2 3 4 5 6 |
let num1 = 10 let num2 = 20 print("W3Adda - Swift Ternary Operator") let result = (num1 > num2) ? ("num1 is greater than num2") : ("num2 is greater than num1") print(result) |
Output:-