Boolean ? : operation syntax [duplicate] - objective-c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the question mark and the colon (?: ternary operator) mean in objective-c?
I have seen code where it uses a syntax something like...
someValue = someBoolean ? valueOne : valueTwo;
Or something like this.
I've never used this and I'm not sure what it's called.
Please can someone explain how to use it or provide a link to a resource about it.

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

Related

What is Visual Basic's equivalant to Java's "!"?

I would like to know Visual Basic's equivalant to Java's "!"
Example of how it would work in Java:
If !code.DoesExist {
log.info("This code doesn't exist!");
}
Else {
log.info("This code does exist");
}
I hope you understand what I mean.
In my code I need to do the following:
If imgUrl.Contains("imgur") Then
ImagesFound += 1
Select Case ImagesFound
Case 1
imgBox.ImageLocation = imgUrl
End Select
ElseIf !imgUrl.Contains("") Then
'<some code here>
End If
I need it at the 7th line.
Note: I can't just use "Else" I need to specifically point out that if an image with imgur in the HTML source wasn't found, then this and that should happen.
As per suggestion, here is more elaborated answer :
Not Keyword : Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression.
For more info : https://msdn.microsoft.com/en-us/library/2cwcswt4.aspx
<> : Checks if the values of two operands are equal or not; if values are not equal, then condition becomes true.
For more info : http://www.tutorialspoint.com/vb.net/vb.net_operators.htm

Ternary operator error - "Expected expression"

I haven't used the ternary operator much and I'm getting an error on this:
(isInitializing) ? (return YES) : (isInitializing = 1);
Error is: "Expected Expression" and it's pointing to return YES.
Don't use the Ternary Operator to "do stuff" but to return one of two values.
So this is a valid case:
NSString *something = (isInitializing ? #"value a" : #"value b");
In your case, you might want to do this instead:
if (isInitializing) {
return YES;
} else {
isInitializing = 1;
}
The ternary operator is used to return one of two values depending on a condition. It is not so much used to execute statements, hence the return is a bit of a problem. I would rather use an if when you do not want to distinguish values, but rather have two different execution paths.

What is the equivalent of else do nothing using the conditional operator?

I want to know what is the equivalent of this if statement:
if (condition) {
// do something
}else{
// do nothing
}
Using the conditional operator:
(condition) ? // [do nothing] : {do nothing} "
It's not possible to "do nothing" using the conditional operator. You always have to have valid expressions on both sides, although both expressions can be casted to void.
This is one of the dis-advantage of ternary operator ( ?: ).
It needs expressions in all the three places. You cant skip any of them.
You can do some tweak on it, however its True-part and / or False-part can be assigned to the same as :
int big=100;
big= (10 > 100) ? 0 : big;
if (!condition) {
// do something
}else{
// do nothing
}
Take a look at the !before contition now :-)
The ! before the condition just switches the "if", to "if not"...
Is that what you have been searching for?
originalValue = (condition) ? newValue : originalValue
The compiler should then remove the unnecessary assign of originalValue to itself.
GCC had an extension to do give you something more to what you where looking for, something like
originalValue = condition ?: newValue;
So it may be available in clang also. You would have to ! the condition though.
you could do something like this
someBool ? [self someFunction] : (^{})(); //empty block
In normal code the answer is there is no equivalent - all sub expressions of an expression must have a value, but...
the following is not a recommendation
Something along the lines of the following should work in the general case:
condition ? ( (^{ do something })(), 0 ) : 0;
That is for the general case. If do something is a single, non-compound, statement; such as a method call; then the block can be dropped to give:
condition ? (do something, 0) : 0;
Again this is NOT recommended in real code!

Why use double parentheses in init methods, or is 1 == (1)?

What do parentheses do when evaluating some meaning?
I have faced this in code, when something is checked and they use
if ( (some condition that returns 1) )
{
code
}
So my question is, does this evaluate to true? I would think that it is always false since (1) does not return anything?
Edit: clarification, question is why double parenthesis in if? I know that 1 is true.
The additional parentheses are used when an assignment is used for its truth value. They allow the compiler to distinguish between
if ((var = expr))
which signals intentional combination of assignment and truth value test, and
if (var = expr)
as an unintentional misspelling of if (var == expr).
The convention, carried over from C and C++, is for the compilers to warn on if (var = expr) as a possible misspelling of if (var == expr). They don't warn on if ((var = expr)), because the extra set of parentheses signals to the compiler that the assignment was intended. As rob mayoff explains, clang has a special case not to warn for certain assignments to self, but for many coders the habit remained.
As others said, the generated code is exactly the same with and without the extra parens.
If you write,
if (self = [super init]) { // Warning
// ...
}
The compiler will give you a warning, because it thinks you might have mistyped = as ==. If you add a second set of parentheses, the warning goes away.
if ((self = [super init])) { // No warning
// ...
}
So the extra parentheses are there to make typos less likely. The parentheses do not change the value of the expression.
In general 0 equates to false, NOT 0 to true.
This link explains bool in objective-c: http://www.mindsizzlers.com/2010/04/objective-c-and-the-properties-of-bool/
true and false value of bool and int
boolean value of false is equivalent to the int value of 0.
boolean value of true is equivalent to the int value of non-zero (e.g. 1, 10, 3000, etc)
For example, consider an example of C code below:
bool bValue;
int nValue;
bValue = true;
nValue = 1;
if (bValue == nValue) {
printf("bValue and nValue are the same!\n");
}
// output: bValue and nValue are the same!
Wrapped with multiple parenthesis:
The following two snippets returns exactly the same results.
if ((((((((((((((((((((1)))))))))))))))))))) {
printf("Hello World!\n");
}
returns the same result as:
if (1) {
printf("Hello World!\n");
}
Expression in if statement
Within your given if statement, you must have an expression that resolves to either true or false value. Please refer to this page for example of expression.

"used struct type value where scalar is required" at .layer.position

I want to make a selection before apply one of two animations,
what I thought is: make a Point one, if my myImageView is at the Point one, then apply animationNo1, else apply animationNo2, but I got this:"used struct type value where scalar is required", at line if (myImageView.layer.position = one)
What I do? how can I fix this?
Does anyone know exactly what makes the problem happen?
CGPoint one = CGPointMake(myImageView.layer.position.x, 100);
if (myImageView.layer.position = one)
{
animationNo1
}
else
{
animationNo2
}
First of all, your if-statement will not do what you think. If you want to compare something you have to use == (ie 2 =)
and you can't compare CGPoints like this.
use
if (CGPointEqualToPoint(one, self.view.layer.position))
if (myImageView.layer.position = one) { animationNo1 }
should be
if (CGPointIsEqualToPoint(myImageView.layer.position, one)) { animationNo1 }
You used a single = meaning assignment, rather than a == for comparison. But the == wouldn't do what you wanted here anyway.
You are passing a struct (int this case position) instead of a scalar. To do what you want you need to use CGPointIsEqualToPoint:
if (CGPointEqualToPoint(one, self.view.layer.position))
Full code with corrections:
CGPoint one = CGPointMake(myImageView.layer.position.x, 100);
if (CGPointEqualToPoint(one, self.view.layer.position))
{
animationNo1
}
else
{
animationNo2
}
Also, as others have pointed out: Be careful about = vs ==. They are different. In this case you don't use == for comparison fortunately, but if you use = for other stuff it will make it true instead of checking to see if it is true.