casillas
casillas

Reputation: 16793

Using Ternary operation in the if condition - Objective C

I am trying to check to find out whether or not numberOfItemsPerSection is bigger than 3 in the if condition. It always returns true. Then I decided to debug.

How is it possible that indexPath.row equals to 1 and numberOfItemsPerSection = 20 and it goes into to the if condition.

What am I doing wrong by using the following ternary operator?

if(indexPath.row == (numberOfItemsPerSection > 3) ? (numberOfItemsPerSection-4) : numberOfItemsPerSection)
{


}

Upvotes: 1

Views: 976

Answers (3)

Laxman Sahni
Laxman Sahni

Reputation: 612

NSInteger desiredRow = numberOfItemsPerSection > 3 ? (numberOfItemsPerSection-4) : numberOfItemsPerSection;
if(indexPath.row == desiredRow) { ... // do your coding }

Upvotes: 3

Khanh Nguyen
Khanh Nguyen

Reputation: 11134

You can write:

if (indexPath.row == (numberOfItemsPerSection > 3 ? numberOfItemsPerSection - 4 : numberOfItemsPerSection)) { ... }

Or if you don't want to hurt your eyes:

BOOL desiredRow = numberOfItemsPerSection > 3 ? numberOfItemsPerSection - 4 : numberOfItemsPerSection;
if (indexPath.row == desiredRow) { ... }

Upvotes: 1

Apurv
Apurv

Reputation: 17186

Use parenthesises to resolve priority. Change the condition by below way. Just cover your turnery condition with parenthesis. It will resolve the turnery operator first and then it will compare it to indexPath.row.

if(indexPath.row == ((numberOfItemsPerSection > 3) ? (numberOfItemsPerSection-4) : numberOfItemsPerSection))

Upvotes: 4

Related Questions