What does the question mark and the colon (?: ternary operator) mean in objective-c?

Objective CCSyntaxOperatorsConditional Operator

Objective C Problem Overview


What does this line of code mean?

label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;

The ? and : confuse me.

Objective C Solutions


Solution 1 - Objective C

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

Solution 2 - Objective C

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.

Solution 3 - Objective C

Simply, the logic would be

(condition) ? {code for YES} : {code for NO}

Solution 4 - Objective C

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!

Solution 5 - Objective C

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;

Solution 6 - Objective C

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;

Solution 7 - Objective C

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;

Solution 8 - Objective C

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:

  1. if an object is nil, it will return false as boolean;
  2. Ternary Operator's second parameter can be empty, as it will return the result on the left of '?'

So let say you write:

[self getSomeString] != nil?: @"";

the second parameter is returning a boolean value, thus a exception is thrown.

Solution 9 - Objective C

>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.

Solution 10 - Objective 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;

Solution 11 - Objective C

int padding = ([[UIScreen mainScreen] bounds].size.height <= 480) ? 15 : 55;

means

int padding; 
if ([[UIScreen mainScreen] bounds].size.height <= 480)
  padding = 15;
else
  padding = 55; 

Solution 12 - Objective C

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#).

Solution 13 - Objective C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondanielreiserView Question on Stackoverflow
Solution 1 - Objective CBarry WarkView Answer on Stackoverflow
Solution 2 - Objective CSeanView Answer on Stackoverflow
Solution 3 - Objective CVarun GoyalView Answer on Stackoverflow
Solution 4 - Objective CBruno BronoskyView Answer on Stackoverflow
Solution 5 - Objective CBrianView Answer on Stackoverflow
Solution 6 - Objective CDietrich EppView Answer on Stackoverflow
Solution 7 - Objective CClaus BrochView Answer on Stackoverflow
Solution 8 - Objective CBananZView Answer on Stackoverflow
Solution 9 - Objective ChandiansomView Answer on Stackoverflow
Solution 10 - Objective CcdhwView Answer on Stackoverflow
Solution 11 - Objective CAtefView Answer on Stackoverflow
Solution 12 - Objective CDavid A. GrayView Answer on Stackoverflow
Solution 13 - Objective Cuser5503563View Answer on Stackoverflow