Swift Ternary Conditional
The ternary conditional operator is a shorthand way of evaluating a condition and assigning a value based on the outcome. Swift offers an easy-to-use way to write conditional statements by using the ternary conditional operator.
Syntax
(condition) ? valueIfTrue : valueIfFalse
The ternary conditional operator consists of three parts:
- A condition that evaluates to either true or false
- The value to return if the condition evaluates to true
- The value to return if the condition evaluates to false
Example
Here is an example of using the ternary conditional operator in Swift:
let age = 25
let drinkAllowed = (age >= 21) ? "Yes" : "No"
print("Can I drink? \(drinkAllowed)")
Output:
Can I drink? Yes
Explanation
In this example, we declare a variable age
and set its value to 25
. We then use the ternary conditional operator to evaluate whether the age is greater or equal to 21. If the condition evaluates to true, then the string "Yes" is assigned to the drinkAllowed
variable. If the condition evaluates to false, then the string "No" is assigned to the drinkAllowed
variable. Finally, we print the value of the drinkAllowed
variable.
Use
The ternary conditional operator provides a concise and readable way to write conditional statements. It is commonly used to assign values to variables based on a condition. It is also useful when you need to make a decision between two possible values, such as when formatting text.
Important Points
- The ternary operator is a shorthand way of writing conditional statements in Swift
- It consists of a condition, a value to return if the condition is true, and a value to return if the condition is false
- It is commonly used to assign values to variables based on a condition
- The ternary operator can be used to make decisions between two possible values
Summary
The ternary conditional operator provides a clear and concise way to write conditional statements in Swift. It is a powerful tool for assigning values to variables based on conditions and for making decisions between two possible values. You can use this operator to make your code more readable and efficient.