如何为数组进行切换?

Mic*_*ker 5 arrays switch-statement swift

这是我的代码:

var animalArray = ["cow","pig"]

switch animalArray {
case ["cow","pig"],["pig","cow"]:
    println("You Win!")
default:
    println("Keep Trying")
Run Code Online (Sandbox Code Playgroud)

我得到错误:"类型'数组'不符合协议'IntervalType'"的行"case ["cow","pig"],["pig","cow"]:".我究竟做错了什么?

jwl*_*ton 2

switch声明需要一个Int. 想一想:

var animalDict: [String: Int] = ["cow": 0,"pig": 1]
var animalSelection: Int = animalDict["cow"]!

switch animalSelection {
case 0:
    println("The Cow Wins!")
case 1:
    println("The Pig Wins!")
default:
    println("Keep Trying")
}

//prints "The Cow Wins!"
Run Code Online (Sandbox Code Playgroud)


编辑1:

感谢大家的评论。我认为这是更健壮的代码:

var animalDict: [String: Int] = ["cow": 0,"pig": 1]
var animalSelection: Int? = animalDict["horse"]

if animalSelection as Int? != nil {
   switch animalSelection! {
   case 0:
       println("The Cow Wins!")
   case 1:
       println("The Pig Wins!")
   default:
       println("Keep Trying")
   }
} else {
    println("Keep Trying")
}

//prints "Keep Trying"
Run Code Online (Sandbox Code Playgroud)

The Cow Wins如果我说:它仍然会打印:

var animalSelection:Int? = animalDict["cow"]
Run Code Online (Sandbox Code Playgroud)


编辑2:

根据@AirSpeedVelocity的评论,我测试了以下代码。比我自己的代码优雅得多:

var animalDict: [String: Int] = ["cow": 0,"pig": 1]
var animalSelection = animalDict["horse"]

switch animalSelection {
case .Some(0):
    println("The Cow Wins!")
case .Some(1):
    println("The Pig Wins!")
case .None:
    println("Not a valid Selection")
default:
    println("Keep Trying")
}
Run Code Online (Sandbox Code Playgroud)

  • “switch 语句需要一个整数。” 不,不是。Swift 中的开关适用于许多不同的类型。它只是不匹配开箱即用的数组。 (4认同)