Kero
Kero

Reputation: 21

Ternary Operator / Replacing if/else with ternary operator

I am trying to replace an if else statement with a ternary operator

if the cost of vodka $24 return at discount price 18 (24 *.75)

This if else loop works fine and gives me the desired result but when i try to convert it to ternary I get "expected ':'" error in xcode. What am I doing wrong here?

ternary operator works like this (condition) ? (executeFirst) : (executeSecond)

here is what I have:


NSUInteger cost = 24;
if (cost == 24) {
    return cost *= .75);
} else {
    return nil;
}    

NSUInteger cost = 24;
(cost = 24) ? return cost *= .75 : return nil;

return cost;

}

Upvotes: 0

Views: 2189

Answers (4)

chrisamanse
chrisamanse

Reputation: 4319

Ternary operator is used to assign a value to some variable.

Use

cost = (cost == 24) ? cost * 0.75 : cost;

or:

return (cost == 24) ? cost*0.75 : cost;

Note the difference between '==' and '='. You must have made a typo or forgot about it in your code. '==' sign checks if left and right values are equal, and '=' assigns the right value to the left side (a variable).

Upvotes: 2

Bogdan Kuštan
Bogdan Kuštan

Reputation: 5577

You should assign ternary operator value to some variable, o return it.

NSUInteger cost = 24;
cost = (cost == 24) ? cost * .75 : nil;
return cost;

Or

NSUInteger cost = 24;
return (cost == 24) ? cost * .75 : nil;

Upvotes: 0

Adam Evans
Adam Evans

Reputation: 2082

The ternary operator has to evaluate to something (think of it as a mini function that HAS TO return a value). For the ternary condition ? one : two, you can't have statements (e.g. x = 3) at one and two; they must be expressions. So in your case it would be

return (cost == 24 ? 0.75 * cost : nil);

Upvotes: 0

missimer
missimer

Reputation: 4079

What you want is something like:

NSUInteger cost = 24;
return (cost == 24) ? cost *= .75 : return nil;

2 things:

  1. The first part of the ternary operator (the condition) should be a boolean, you previously had an assignment (== vs. =)

  2. Return the result of the ternary operator.

Upvotes: 0

Related Questions