我想比较三个随机生成的数字,看看它们中的任何两个是否相等。我有一个if语句,但是如果可能的话,我真的想把两个if语句组合成一个。我想有一些方法可以使用或,但它只是一个二元运算符。有没有办法使用?并在其他if语句中创建三元参数?
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"
}
答案 0 :(得分: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"
}
答案 1 :(得分: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"
}
答案 2 :(得分: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)
这适用于任何数量的值。