some tech talk about conditional operator picked from Programming in Objective-c 6th edition
A non-ANSI extension to the syntax of the conditional operator, which is supported by Xcode, is shown here:
condition ?: expression
In this syntax, condition is evaluated, and if true, then the value of the operation is condition. If condition is false, then the value of the operation is expression.Logically, this syntax is identical to the following:
condition ? condition : expression
However, in the former case condition will only be evaluated once, whereas in the latter case
it could be evaluated twice.
Here’s how you could set the value of result to index if it were nonzero, or to -1 otherwise:
result = index ?: -1;
s = ( x < 0 ) ? -1 : x * x;
The condition x < 0 is first tested when the previous statement is executed. Parentheses are generally placed around the condition expression to aid in the statement’s readability. This is usually not required, though, because the precedence of the conditional operator is very low(lower, in fact, than all other operators but the assignment operators and the comma operator).
If the expression after the : (the “else” part) consists of another conditional operator, you
can achieve the effects of an else if clause. For example, the sign function implemented in Program 6.6 can be written in one program line using two conditional operators, as follows:
sign = ( number < 0 ) ? -1 : (( number == 0 ) ? 0 : 1);
If number is less than zero, sign is assigned the value -1; if number is equal to zero, sign is assigned the value 0; otherwise, it is assigned the value 1. The parentheses around the “else” part of the previous expression are actually unnecessary. This is because the conditional opera- tor associates from right to left, meaning that multiple uses of this operator in a single expression, such as in
e1 ? e2 : e3 ? e4 : e5
group from right to left and therefore are evaluated as follows:
e1 ? e2 : ( e3 ? e4 : e5 )
Conditional expressions don’t have to be used on the right side of an assignment; they can be used in any situation in which expressions can be used. This means you can display the sign of the variable number without first assigning it to a variable using an NSLog statement, as shown here:
NSLog (@"Sign = %i", ( number < 0 ) ? -1
: ( number == 0 ) ? 0 : 1);