A standard if
/else
statement can get pretty lengthy - at least 5 lines of code. Many developers prefer to keep their code as concise as possible and favor a shorter syntax. Swift allows us to minimize our if
/else
statements with a tool called the ternary conditional operator.
The ternary conditional operator, denoted by a ?
, offers a shorter, more concise alternative to a standard if/else
statement. It executes one of two expressions depending on the boolean result of the condition.
A ternary conditional consists of three parts in the following format:
- A is the condition to check for
- B is the expression to use if the condition is
true
- C is the expression to use if the condition is
false
Suppose we’d like to check if an order was placed successfully by a customer and print them a message. We can set up the following if
/else
statement:
var orderSuccessfullyPlaced = false if orderSuccessfullyPlaced { print("Your order was received.") } else { print("Something went wrong.") }
Since the value of our condition is false
, the second code block executes and Something went wrong.
will print.
With a sprinkle of ternary magic, we can transform our code into one line, a one liner, and achieve the same result:
orderSuccessfullyPlaced ? print("Your order was received.") : print("Something went wrong.")
Note that although the ternary conditional operator helps us develop shorter code, overusing this syntax can also result in your code being difficult to read. So, use it sparingly!
Instructions
In Sailing.swift, we’ve set up an if
/else
statement that checks for windiness.
On the following line, rewrite the conditional in ternary format.