I would like to do a switch case for multiples values, where those values are get from keys of a dictionary.
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")
}
How can I get myDict keys and transform them to tuples (or something else)) ?
I tried Array(myDict.keys)
but it fails :
Expression pattern of type 'Array<String>' cannot match values of type
'String'
You can achieve what you want with a where
clause. Here's how to do it.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With