微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数组 – 如何为数组进行切换?

这是我的代码

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

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

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

解决方法

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

编辑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"

如果我说:如果我说:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐