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

数组 – 如何为数组进行切换?,第1张

概述这是我的代码: var animalArray = ["cow","pig"]switch animalArray {case ["cow","pig"],["pig","cow"]: println("You Win!")default: println("Keep Trying") 我得到错误:“类型’数组’不符合协议’IntervalType’”的行“case [”c 这是我的代码:

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

以上是内存溢出为你收集整理的数组 – 如何为数组进行切换?全部内容,希望文章能够帮你解决数组 – 如何为数组进行切换?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1006391.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-22
下一篇2022-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存