2

我有一个问题,但我无法找到答案。有什么办法可以减少Objective-C中的以下表达式?

if ((r != 1) && (r != 5) && (r != 7) && (r != 12)) {
   // The condition is satisfied
}else{
   // The condition isn't satisfied
}

例如(不工作):

if (r != (1 || 5 || 7 || 12)) {
   // The condition is satisfied
}else{
   // The condition isn't satisfied
}

谢谢!

4

2 回答 2

4

您可以使用NSSet,如下所示:

NSSet *prohibited = [NSSet setWithArray:@[@1, @5, @7, @12]];
if (![prohibited containsObject:[NSNumber numberWithInt:r]]) {
    // The condition is satisfied
} else {
    // The condition isn't satisfied
}

如果一组数字包含一组固定的数字,例如在您的示例中,您可以创建NSSet *prohobited一个静态变量,并对其进行一次初始化,而不是像我上面的示例中那样每次都进行。

于 2012-12-31T00:20:25.410 回答
0

你也可以switch像这样使用

switch (r)
{
    case 1:
    case 5:
    case 7:
    case 12:
        // r is having 1,5,7 or 12
        break;
    default:
        // r is having other values
}
于 2012-12-31T06:18:09.940 回答