I’ve always been fond of the conditional operator in C, which is essentially a terse way to write an if/else statement. Given this operator works with three operands, it is often fondly referred to as the ternary operator.
The conditional looks as follow:
condition-test ? first-expression : second-expression
If the condition-test is nonzero, the first-expression is evaluated, otherwise the second-expression is evaluated.
// Traditional approach if (x > 0) str = @"positive"; else str = @"negative"; // Conditional operator str = x > 0 ? @"positive" : @"negative";
Nesting Conditional Operators
Extending the example above, we can update the code for the case where x is neither positive or negative (x is zero), using nested conditionals:
// Traditional approach if (x > 0) str = @"positive"; else if (x < 0) str = @"negative"; else str = @"zero"; // Conditional operator str = x > 0 ? @"positive" : x < 0 ? @"negative" : @"zero";
As shown above, based on the association of parameters, no parenthesis are necessary, however, I find this much easier to read:
str = x > 0 ? @"positive" : (x < 0 ? @"negative" : @"zero");
Good Use Case
I find the conditional operator useful when creating messages in which part of the message may be plural or singular depending on the value of a variable.
It’s not much more work to make messages appear as expected, for example, how often have you seen a message from an application that looks similar to this “1 file(s) downloaded” where ideally the message would read “1 file downloaded” – not a big deal, however, it’s a trivial amount of code to get this right:
int x = 1; NSString *str = [NSString stringWithFormat:@"%d file%s downloaded", x, (x > 1 ? "s" : "")];
Sometimes it’s the little things that will setup you apart in a crowd of developers.