2016-05-14 34 views
0

我想比較三個隨機生成的數字,看看它們中的任何兩個是否相等。我有一個if語句可行,但如果可能的話,我真的想將其他兩個if語句合併爲一個。我認爲必須有一些方法來使用,但它只有一個二元運算符。有沒有辦法使用並在另一個語句中做出三元論證?使用If語句檢查3種可能性

 if aRand == bRand && bRand == cRand{ 
      resultLabel.text = "3 out of 3" 
     } else if 
      (aRand == bRand || aRand == cRand) { 
      resultLabel.text = "2 out of 3" 
     } else if 
     (bRand == cRand) { 
     resultLabel.text = "2 out of 3" 
     } else { 
      resultLabel.text = "No Match" 
     } 

回答

4

其實這是

if aRand == bRand || aRand == cRand || bRand == cRand 

這裏一個swiftier表達

let rand = (aRand, bRand, cRand) 
switch rand { 
    case let (a, b, c) where a == b && b == c : resultLabel.text = "3 out of 3" 
    case let (a, b, c) where a == b || a == c || b == c : resultLabel.text = "2 out of 3" 
    default : resultLabel.text = "No match" 
} 
+0

謝謝,如果aRand == bRand || aRand == cRand || bRand == cRand是我需要的。我覺得這很容易,我很欣賞這些迴應。我很積極,我嘗試了這個,原來並沒有工作,但我又試了一次,這次它做到了。 – Chawker21

+0

我也喜歡更快捷的表達方式,它看起來更適合於擴展。我會嘗試一下,看看我可以去哪裏。再次感謝! – Chawker21

1

較短方式:

if (aRand == bRand && bRand == cRand) { 

    resultLabel.text = "3 out of 3" 

} else if (aRand == bRand || bRand == cRand || aRand == cRand) { 

    resultLabel.text = "2 out of 3" 

} else { 

    resultLabel.text = "No Match" 
} 
1

如果我正確理解你的算法,你能避免if乾脆:

let aRand = 0 
let bRand = 1 
let cRand = 1 

let allValues = [aRand, bRand, cRand] 
let uniqueValues = Set(allValues) 

let text: String 

if (uniqueValues.count == allValues.count) { 
    text = "No match" 
} else { 
    text = String(format: "%i out of %i", allValues.count - uniqueValues.count + 1, allValues.count) 
} 

print(text) 

這將爲任何工作值的數量。