2012-12-31 58 views
2

我有一個問題,我一直沒能找到答案。 有什麼辦法可以在Objective-C中減少以下表達式嗎?「if-else」with multiple OR/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 
} 

謝謝!

+0

你可以刪除一些括號。 – alex

+0

這將是一個更長的表達式,但您可以創建一個1,5,7和12的整數數組,並檢查它是否包含「r」。更多的代碼,但更容易維護。 –

+0

嘗試閱讀關於德摩根法律。 – user1929959

回答

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一個靜態變量,一旦初始化,而不是像我上面的例子那樣每次都做。

+0

哇!我認爲這是一個不錯的選擇,謝謝! – mhergon

+0

由於您已經在使用現代語法,您還可以使用'@(r)'創建NSNumber – Anurag

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 
}