5

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'
Caleb Kleveter
  • 10,806
  • 8
  • 58
  • 83
Nahouto
  • 1,315
  • 1
  • 18
  • 30
  • check [SO](http://stackoverflow.com/a/28658885/2710486) – zc246 Feb 01 '16 at 13:52
  • I already get an Array, but how to transform it to tuple ? – Nahouto Feb 01 '16 at 13:53
  • What do you want for tuple? Dict and Array gives almost everything you would need. – zc246 Feb 01 '16 at 13:55
  • switch statement does not on an Array, that's why I was trying to convert the dictionary keys to tuple. But I was in a wrong way, and Marc's solution is clearly the best. – Nahouto Feb 01 '16 at 14:23
  • What you really want is to check key existence with `dict[key] != nil`. Don't think switch statement is suitable here. BTW, don't forget your `break` in switch statement. – zc246 Feb 01 '16 at 14:27
  • I can do like that : if key exist {do that} else {switch statement} but it is very long. Thanks for the break tip, it prevents the code to fall in two case statements – Nahouto Feb 01 '16 at 14:34
  • You don't want to fall through default. – zc246 Feb 01 '16 at 14:35
  • @zcui93 In Swift, `switch` cases break by default. You have to use the `fallthrough` keyword to get the C behavior of falling through to the next case. – Marc Khadpe Feb 01 '16 at 14:35
  • Thanks man. @MarcKhadpe – zc246 Feb 01 '16 at 14:36

1 Answers1

13

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")
}
Marc Khadpe
  • 1,962
  • 14
  • 14