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
  • 11,170
  • 8
  • 62
  • 92
Nahouto
  • 1,375
  • 2
  • 18
  • 31
  • 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

2 Answers2

14

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
  • 2,012
  • 16
  • 14
-1

Marc's answer is predicated on defining the key you're looking for first. If you want to iterate through all your keys, then run a for-loop over your dictionary using the tuples like you suggested:

let dictionary = ["Apple": 1, "Banana": 2, "Cherry": 3]

for (key, value) in dictionary {
    switch key {
    case "Apple":
        print("Apple's value is \(value)")
    case "Banana":
        print("Banana's value is \(value)")
    case "Cherry":
        print("Cherry's value is \(value)")
    default:
        print("Unrecognized key: \(key)")
    }
}

Note: The order of keys and values in a dictionary is not fixed, so the order of the print statements might be different each time you run the code.

trpubz
  • 7
  • 4