The operator switchrequires Int. Think about it:
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")
}
Change 1:
Thank you all for your comments. I think this is more reliable 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")
}
He will print The Cow Winsif I say:
var animalSelection:Int? = animalDict["cow"]
Edit 2:
Based on @AirSpeedVelocity's comments, I checked 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")
}