The ternary operator in Swift

Federica Benacquista
2 min readMay 14, 2021

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()



Federica Benacquista

I’m a self taught iOS developer and soon to be entrepreneur. I like to explain tricky concepts as easily as possible and it’s exactly what I do here.