What does this line of code mean?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
The ?
and :
Ternary operator example.If the value of isFemale boolean variable is YES, print "GENDER IS FEMALE" otherwise "GENDER IS MALE"
? means = execute the codes before the : if the condition is true.
: means = execute the codes after the : if the condition is false.
Objective-C
BOOL isFemale = YES; NSString *valueToPrint = (isFemale == YES) ? @"GENDER IS FEMALE" : @"GENDER IS MALE"; NSLog(valueToPrint); //Result will be "GENDER IS FEMALE" because the value of isFemale was set to YES.
For Swift
let isFemale = false let valueToPrint:String = (isFemale == true) ? "GENDER IS FEMALE" : "GENDER IS MALE" print(valueToPrint) //Result will be "GENDER IS MALE" because the isFemale value was set to false.
This is the C ternary operator (Objective-C is a superset of C):
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
is semantically equivalent to
if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}
The ternary with no first element (e.g. variable ?: anotherVariable
) means the same as (valOrVar != 0) ? valOrVar : anotherValOrVar
Simply, the logic would be
(condition) ? {code for YES} : {code for NO}
It's just a short form of writing an if-then-else statement. It means the same as the following code:
if(inPseudoEditMode)
label.frame = kLabelIndentedRect;
else
label.frame = kLabelRect;
It's the ternary or conditional operator. It's basic form is:
condition ? valueIfTrue : valueIfFalse
Where the values will only be evaluated if they are chosen.
This is part of C, so it's not Objective-C specific. Here's a translation into an if
statement:
if (inPseudoEditMode)
label.frame = kLabelIndentedRec;
else
label.frame = kLabelRect;