Swift Short Hand If…Else

Swift Short Hand If…Else

Use the ternary operator condition ? a : b for concise conditional expressions.


Basic Ternary Operator

Use the ternary operator to choose between two values in a single expression.

Example

let age = 20
let status = (age >= 18) ? "Adult" : "Minor"
print(status)

This example returns “Adult” when age >= 18, otherwise “Minor”.


REMOVE ADS


Choose the Minimum

Use a ternary expression to select the smaller of two values.

Example

let a = 5, b = 9
let min = (a < b) ? a : b
print(min)

This prints the smaller number.

If a is not less than b, the expression returns b.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *