开发者

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

开发者 https://www.devze.com 2022-12-26 15:16 出处:网络
What does this line of code mean? label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect; The ?开发者_StackOverflow中文版 and : confuse me.This is the C ternary operator (Objective-C is

What does this line of code mean?

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

The ?开发者_StackOverflow中文版 and : confuse me.


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


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.


Simply, the logic would be

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


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!


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;


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;


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;


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.


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.


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;


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


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.


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; 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号