Friday, February 10, 2017

Be cautious with the ternary operator

The operators in a programming language, in general, and in Swift, in particular, are of three types:

Unary - that operate on a single target. They can be added before or after the target.

For example -a or !a or a!.

They can also be binary when they are applied to two targets. For example: a + b.

There are also the ternary operators that are applied to three targets. In Swift, we have only one ternary operator that has the format:

condition ? value_if_true : value_if_false

For example:

var interestRate = income < 1000 ? 3 : 5

It is a useful shortcut for

If income < 1000 {
    interestRate = 3
} else {
    interestRate = 5
}

There are some cases when the ternary operator can become confusing.

For example,  in the case when the options for true and false are pretty long:

let message = isAdmin ? “Please enter your admin username and password” : “Please enter your username and password”

Here, and if statement would me the code better

var message: String

If isAdmin {
    message = “Please enter your admin username and password”
} else {
    message = “Please enter your username and password”
}

So, as a conclusion, the ternary operator is good but sometimes replacing it with if statement might be better.

Of course, in our case, the strings need to be replaced with constants and maybe localized, but that is a different topic for another time.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.