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.
Related
I am trying to create a class similar to the built in NSDictionary class, but I want to add some extra functionality and make it easier to use. In the .m file I have the following piece of code:
-(void)newEntryWithKey:(NSString *)theKey andValue:(NSString *)theValue{
if (![theKey isEqual:#""]) && (![theValue isEqual:#""]){
[self.keys addObject:theKey];
[self.values addObject:theValue];
self.upperBound++;
}else{
return
}
}
It gives me an "Expected Identifier" error at the start of the second portion of the if statement after the "&&". Would someone be able to help me with this?
EDIT: The original problem is fixed but now there is a new error at the end of the if statement.
-(void)newEntryWithKey:(NSString *)theKey andValue:(NSString *)theValue{
if (theKey.length && theValue.length) {
[self.keys addObject:theKey];
[self.values addObject:theValue];
self.upperBound++;
}else{
return
} //<-- error here "Expected expression"
}
It should be:
if (![theKey isEqual:#""] && ![theValue isEqual:#""]) {
Though a better check for non-empty strings would be:
if (theKey.length && theValue.length) {
Your original if statement will give incorrect results if either theKey or theValue is nil. My 2nd option works in either case.
Update:
The problem with the updated code is the missing ; after the return statement.
Usually after if you should have one condition in parentheses. You're missing parentheses.
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!
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;
}
I have an object that returns a value if successful and false (or nil) if it failed.
i want to assign that value to a variable
if(var1 = [object foo])
{
//if the [object foo] returned a variable, goes here
}
else
{
//[object foo] returned FALSE (or nil), go here
}
can an If statement detected if an assignment was valid?
This is all right but will generate a warning, since this is a common typo (= instead of ==). To silence that warning add another set of parentheses like this:
if ((var = [object foo])) ...
Since this easily can lead to misunderstandings a lot of people will advise against doing this. For a simple if statement this is much clearer to do the assignment first:
var = [object for];
if (var) ...
In while loops this is more useful, but also considered harmful by many people.
Not sure I understand your question, but let me try and explain a few situations you can check
1) Property contains value
if ([object foo])
{
// If foo has a value associated to it that is not nil/false/zero
}
else
{
// If foo equals nil, false or zero
}
2) Assignment to a variable was successful
if ((bar = [object myMethod]))
{
// If myMethod returns any non-nil value
}
else
{
// If myMethod returns nil
}
3) Previous assignment of a variable was successful
bar = [object myMethod];
if (bar)
{
// If bar has a value associated to it that is not nil/false/zero
}
else
{
// If bar equals nil, false or zero
}
use == instead of = in the if statement.
before the if statement, you may have var1 = [object foo]
see comparison operators
If you mean by valid that the variable contains an expected result, you can just perform another if on the variable against the expected result, or null to check it.
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.