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

Swift:switch case从字典键中复用值

发布时间:2020-12-14 04:48:00 所属栏目:百科 来源:网络整理
导读:我想为多个值做一个切换案例,其中这些值来自字典的键. myDict = ["dog": "waf","cat": "meaow","cow":"meuh"]let animal = "cat"switch animal {case myDict.keys : print(myDict[animal])case "lion" : print("too dangerous !")}default : print("unknown
我想为多个值做一个切换案例,其中这些值来自字典的键.

myDict = ["dog": "waf","cat": "meaow","cow":"meuh"]
let animal = "cat"

switch animal {

case myDict.keys :
   print(myDict[animal])

case "lion" :
   print("too dangerous !")
}

default :
   print("unknown animal")
}

如何获取myDict键并将其转换为元组(或其他))?
我尝试了Array(myDict.keys),但它失败了:

Expression pattern of type 'Array<String>' cannot match values of type
'String'

解决方法

你可以用where子句实现你想要的.这是怎么做的.

let myDict = ["dog": "waf","cow":"meuh"]
let animal = "cat"

switch animal {

case _ where myDict[animal] != nil :
    print(myDict[animal])

case "lion" :
    print("too dangerous !")

default :
    print("unknown animal")
}

(编辑:李大同)

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

    推荐文章
      热点阅读