What does this line of code mean?
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
The ?
and :
I just learned something new about the ternary operator. The short form that omits the middle operand is truly elegant, and is one of the many reasons that C remains relevant. FYI, I first really got my head around this in the context of a routine implemented in C#, which also supports the ternary operator. Since the ternary operator is in C, it stands to reason that it would be in other languages that are essentially extensions thereof (e. g., Objective-C, C#).
It is ternary operator, like an if/else statement.
if(a > b) {
what to do;
}
else {
what to do;
}
In ternary operator it is like that: condition ? what to do if condition is true : what to do if it is false;
(a > b) ? what to do if true : what to do if false;
Building on Barry Wark's excellent explanation...
What is so important about the ternary operator is that it can be used in places that an if-else cannot. ie: Inside a condition or method parameter.
[NSString stringWithFormat: @"Status: %@", (statusBool ? @"Approved" : @"Rejected")]
...which is a great use for preprocessor constants:
// in your pch file...
#define statusString (statusBool ? @"Approved" : @"Rejected")
// in your m file...
[NSString stringWithFormat: @"Status: %@", statusString]
This saves you from having to use and release local variables in if-else patterns. FTW!
Fun fact, in objective-c if you want to check null / nil For example:
-(NSString*) getSomeStringSafeCheck
{
NSString *string = [self getSomeString];
if(string != nil){
return String;
}
return @"";
}
The quick way to do it is:
-(NSString*) getSomeStringSafeCheck
{
return [self getSomeString] != nil ? [self getSomeString] : @"";
}
Then you can update it to a simplest way:
-(NSString*) getSomeStringSafeCheck
{
return [self getSomeString]?: @"";
}
Because in Objective-C:
So let say you write:
[self getSomeString] != nil?: @"";
the second parameter is returning a boolean value, thus a exception is thrown.
As everyone referred that, It is a way of representing conditional operator
if (condition){
true
}
else {
false
}
using ternary operator (condition)? true:false
To add additional information, In swift we have new way of representing it using ??
.
let imageObject: UIImage = (UIImage(named: "ImageName")) ?? (initialOfUsername.capitalizedString).imageFromString
Which is similar to
int a = 6, c= 5;
if (a > c)
{
a is greater
} else {
c is greater
}
is equivalent to
if (a>c)?a:c
==> Is equal to if (a>c)?:c
instead of ?:
we can use ??
is swift.
That's just the usual ternary operator. If the part before the question mark is true, it evaluates and returns the part before the colon, otherwise it evaluates and returns the part after the colon.
a?b:c
is like
if(a)
b;
else
c;