2016-05-14 6 views
0

ランダムに生成された3つの数値を比較して、2つの数値が等しいかどうかを比較したいと考えています。私は動作するif文を持っていますが、2つのelse 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

実際にそれがここ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 || aRand == cRand || bRand == cRand 

です:私が正しくあなたのアルゴリズムを理解していれば、

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) 

これはの値の任意の数を動作します。

関連する問題