danielreiser
danielreiser

Reputation: 5360

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

What does this line of code mean?

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

The ? and : confuse me.

Upvotes: 293

Views: 390027

Answers (13)

Varun Goyal
Varun Goyal

Reputation: 732

Simply, the logic would be

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

Upvotes: 70

BananZ
BananZ

Reputation: 1193

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.

Upvotes: 4

handiansom
handiansom

Reputation: 783

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.

Upvotes: 2

Atef
Atef

Reputation: 2902

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; 

Upvotes: 1

Claus Broch
Claus Broch

Reputation: 9212

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;

Upvotes: 4

user5503563
user5503563

Reputation:

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.

Upvotes: 1

David A. Gray
David A. Gray

Reputation: 1075

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

Upvotes: 2

cdhw
cdhw

Reputation: 27

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;

Upvotes: 1

Barry Wark
Barry Wark

Reputation: 107754

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

Upvotes: 455

Sean
Sean

Reputation: 62472

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.

Upvotes: 190

Bruno Bronosky
Bruno Bronosky

Reputation: 70329

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!

Upvotes: 36

Brian
Brian

Reputation: 8823

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;

Upvotes: 17

Dietrich Epp
Dietrich Epp

Reputation: 213318

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;

Upvotes: 4

Related Questions