swift将switch语句中的tuple与or进行比较

时间:2014-07-29 04:00:42

标签: swift switch-statement tuples

如何在switch语句中为元组提供多种可能性?请注意我已经尝试了

var duel = (comp1CurrCard, comp2CurrCard)
    switch duel {

        case (1||14||27||40, 1||14||27||40):
            println("ace duel")

        case (2,15,28,41),(2,15,28,41):
            println("2 duel")
    }

comp1CurrCardcomp2CurrCard都是Int类型。 基本上我想要的是comp1CurrCard == 1 || 14 || 27 || 40&& comp2CurrCard == 1 || 14 || 27 || 40比println(“王牌决斗”)

但是我不知道如何最好地做到这一点,我知道我希望使用switch语句,因为它似乎是解决它的最佳方法

我知道由于错误我做错了什么:P感谢任何帮助!

3 个答案:

答案 0 :(得分:4)

我能想到这个解决方案,

var duel = (2, 2)

switch duel{
case let (m, n) where (m == 1 || m == 14 ||  m == 27 || m == 40) && (n == 2 || n == 14 || n == 27 || n == 40):
  println("ace duel")
case let (m, n) where (m == 2 || m == 15 || m == 28 || m==41) && (n == 2 || n == 15 || n == 28 || n == 41):
  println("2 duel")
default:
  println("No")
}

答案 1 :(得分:0)

也许是这样的:

var duel = (comp1CurrCard, comp2CurrCard)
switch duel {

    case let (a, b) where [1,14,27,40].contains(a) && [1,4,27,40].contains(b):
        println("ace duel")

    case let (a,b) where [2,15,28,41].contains(a) && [2,15,28,41].contains(b):
        println("2 duel")
    default:
        println("something else")
}

答案 2 :(得分:0)

let aceGroup = [1, 14, 27, 40]
let twoGroup = [2, 15, 28, 41]
switch (comp1CurrCard, comp2CurrCard) {
case _ where contains(aceGroup, comp1CurrCard) && contains(aceGroup, comp2CurrCard):
    println("ace duel")
case _ where contains(twoGroup, comp1CurrCard) && contains(twoGroup, comp2CurrCard):
    println("2 duel")
default:
    println("none duel")
}