In the Swift programming language, we have a convenient shorthand version of an if
expression called the ternary conditional operator. It allows you to execute one expression when a condition is true and another expression when the condition is false.
Here is the syntax for the ternary conditional operator:
condition ? value if true : value if false
Let’s illustrate this with an example:
let num1 = 1
let num2 = 2
let smallerNumber = num1 < num2 ? num1 : num2
// smallerNumber == 1
In this example, we use the ternary conditional operator to assign the smaller of two numbers to the smallerNumber
variable. If num1
is less than num2
, the value of num1
is assigned to smallerNumber
. Otherwise, the value of num2
is assigned. The result is that smallerNumber
is assigned the value of 1.
The use of the ternary conditional operator can make your code more concise and easier to read in certain scenarios. However, it is important to use it judiciously and ensure that the resulting code remains clear and maintainable.