The ternary operator in Swift
--
Do you remember those notes kids would pass around when we were in middle school asking “Do you like me”?
The ternary operator is the equivalent of them in code.
When you use the ternary operator you’re asking a question that can either be true or false. When it’s true, the code after the “?” gets executed and when it’s false, the code after the “:” gets executed.
To return to the above example, if we had to express that in code, assuming that “doYouLikeMe” is a boolean variable, we would have:
result = youLikeMe ? true : false
We can see that it behaves exactly like an if-statement:
if youLikeMe {
result = true
} else{
result = false
}
So the logic behind it is the following:
question ? trueExpression : falseExpression
Unlike other languages as Java, in Swift it is not necessary that we assign the result of the ternary expression to a variable, so an as well valid way to use it would be the following line (assuming that both functions are void):
youLikeMe ? weGetTogether() : weStayFriends()
This can be read just like you would read an if statement: “if you like me we get together otherwise we stay friends”.
This super handy tool can quickly become hard to read. Therefore, even if we could check for other conditions in the false part, it’s not recommended:
youLikeMe ? weGetTogether() : weWantToBeFriends ? weStayFriends() : weDontStayFriends() //Correct but not recommended
Using a regular if statement, the above code would look something like this:
if youLikeMe {
weGetTogether()
} else if weWantToBeFriends{
weStayFriends()
} else {
weDontStayFriends()
}