我想为多个值做一个切换案例,其中这些值来自字典的键.
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")
}
Run Code Online (Sandbox Code Playgroud)
如何获取myDict键并将其转换为元组(或其他))?我试过Array(myDict.keys)但它失败了:
Expression pattern of type 'Array<String>' cannot match values of type
'String'
Run Code Online (Sandbox Code Playgroud)
Mar*_*dpe 10
你可以通过一个where子句实现你想要的.这是怎么做的.
let myDict = ["dog": "waf", "cat": "meaow", "cow":"meuh"]
let animal = "cat"
switch animal {
case _ where myDict[animal] != nil :
print(myDict[animal])
case "lion" :
print("too dangerous !")
default :
print("unknown animal")
}
Run Code Online (Sandbox Code Playgroud)