How to make a switch for an array?

arrays, swift, switch-statement

Solution

The `switch` statement requires an `Int`. Think about this:

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!"

Edit 1:

Thanks to all for your comments. I think this is more robust code:

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"

It will still print `The Cow Wins` if I say:

var animalSelection:Int? = animalDict["cow"]

Edit 2:

Based on @AirSpeedVelocity's comments I tested the following code. Much more elegant than my own code:

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")
}

Problem

Here's my code: ``` var animalArray = ["cow","pig"] switch animalArray { case ["cow","pig"],["pig","cow"]: println("You Win!") default: println("Keep Trying") ``` I get the error: "Type 'Array' does not conform to protocol 'IntervalType'" for the line "case ["cow","pig"],["pig","cow"]:". What am I doing wrong?

Original source