[英]Objective-C IF statement with multiple OR statements
I was wondering if there was a simpler way to do multiple OR statements as part of a singe IF statement. 我想知道是否有更简单的方法可以将多个OR语句作为单IF语句的一部分。
Currently I am doing them like this: 目前,我正在这样做:
if ((i == 1) || (i == 4) || (i == 7)) {}
Is there a simpler way? 有没有更简单的方法?
You could use a switch
block with fall through. 您可以使用掉落的switch
块。
switch (i)
{
case 1:
case 4:
case 7:
yourCode;
break;
}
You can use NSArray
's containsObject:
method, like this: 您可以使用NSArray
的containsObject:
方法,如下所示:
if ([@[@1, @4, @7] containsObject:@(i)]) {
...
}
The usefulness of this approach improves with the length of the list: with three items, your solution looks better, but once you cross the limit of about ten numbers, this solution becomes more and more readable: 这种方法的实用性随着列表的长度而提高:通过三个项目,您的解决方案看起来更好,但是一旦您越过了大约十个数字的限制,该解决方案就会变得越来越可读:
if ([@[@1, @3, @12, @17, @23, @27, @31, @41, @43, @57] containsObject:@(i)]) {
...
}
You can make a named array for the list of expected constants @[@1, @4, @7]
to shorten the if
, like this: 您可以为期望常量@[@1, @4, @7]
的列表创建一个命名数组,以缩短if
,如下所示:
NSArray *expect = @[@1, @4, @7];
...
if ([expect containsObject:@(i)]) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.