简体   繁体   English

在if条件下使用三元运算-目标C

[英]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. 我正在尝试检查if条件下numberOfItemsPerSection是否大于3。 It always returns true. 它总是返回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. indexPath.row等于1且numberOfItemsPerSection = 20怎么可能进入if条件。

What am I doing wrong by using the following ternary operator? 使用以下三元运算符,我在做什么错?

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


}

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. 它将首先解析Turnery运算符,然后将其与indexPath.row进行比较。

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

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) { ... }
NSInteger desiredRow = numberOfItemsPerSection > 3 ? (numberOfItemsPerSection-4) : numberOfItemsPerSection;
if(indexPath.row == desiredRow) { ... // do your coding }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM