Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : switch case multiples values from dictionary keys

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'
like image 944
Nahouto Avatar asked Feb 01 '16 13:02

Nahouto


1 Answers

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")
}
like image 198
Marc Khadpe Avatar answered Nov 03 '22 00:11

Marc Khadpe