我想为多个值做一个切换案例,其中这些值来自字典的键.
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") }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。