加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:41:07 所属栏目:百科 来源:网络整理
导读:这是我的代码: var animalArray = ["cow","pig"]switch animalArray {case ["cow","pig"],["pig","cow"]: println("You Win!")default: println("Keep Trying") 我得到错误:“类型’数组’不符合协议’IntervalType’”的行“case [”cow“,”pig“],[”pi
这是我的代码:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读