Boolean ? : operation syntax

6 Solutions Collect From Internet About “Boolean ? : operation syntax”

It’s ternary opertaor.

It evaluates the someBoolean condition.

If it is true then pass the valueOne to someValue

If it is false then pass valueTwo to someValue

It is equal to:

if(someBoolean)
{
   someValue = valueOne;
}
else
{
   someValue = valueTwo;
}

This is a good link which explains about ternary operator

This is called ternary operator ( ?: )

1 ? 2 : 3

1 is the condition.

2 is executed when 1 it is true.

3 is executed when 1 is false.

Similar to: (Below is not a running code, 1,2,3 shows only placeholders for some expressions and statements.

 if(1){ //condition
     2 //true
 }
 else{
     3 //false
 }

You can shorten it as for :

int bigger;
(10<100) ? bigger=100 : bigger=10;

in short way:

int bigger = (10<100) ? 100 : 10 ;

NOTE:

Its precedence order is among the least and it is much slower then if-else and switch case statements.

It is a ternary operator (also known as the conditional operator). You can find explanation at this link.

Basically your expression is saying that if someBoolean is true someValue will get valueOne if not it will get valueTwo.

It is similar to:

 if(someBoolean)
 {
    someValue = valueOne;
 }
 else
 {
    someValue = valueTwo;
 }

which offers less visibility in your code. I recommend using this operator in case you want to assign a value which depends on one condition.

Note that it is an expression not specific to Objective-C, you can use it in C and C++ too.

The result of the assignment is valueOne is the condition is true, and valueTwo if the condition is false.

See it here on wikipedia. It also makes the case with other languages, just skip them and see the C syntax example.

Suppose user needs to answer some question and you change background color of your view to red if he was wrong, green if he was correct.

- (void)handleAnswer:(BOOL)correct {
    UIColor *color = (correct) ? [UIColor greenColor] : [UIColor redColor];
    self.view.backgroundColor = color;
}

It works same as the following

if (someBoolean)
{
    someValue = valueOne;
}
else
{
    someValue = valueTwo;
}