How to "switch" based on keys contained in a dictionary in Swift?

I want to execute different branches based on what keys the dictionary contains, here is some code you can paste into the playfield that shows what I am currently doing:

let dict1 = ["a" : 1, "thingy" : 2]
let dict2 = ["b" : 3, "wotsit" : 4]
let dict = dict1 // Change this line to see different outcomes

if  let valueA = dict["a"],
    let thingy = dict["thingy"] {
        // Code for type with "a" and "thingy" keys
        println("a/thingy")
} else if   let valueB = dict["b"],
            let wotsit = dict["wotsit"] {
        // Code for type with "b" and "wotsit" keys
        println("b/wotsit")
}

      

However, I think it would be more elegantly expressed as a switch statement - something like this:

let dict1 = ["a" : 1, "thingy" : 2]
let dict2 = ["b" : 3, "wotsit" : 4]
let dict = dict1 // Change this line to see different outcomes

switch dict {
case    let a = dict["a"],
        let thingy = dict["thingy"]:
    // Code for type with "a" and "thingy" keys
    println("a/thingy")
case    let b = dict["b"],
        let wotsit = dict["wotsit"]:
    // Code for type with "b" and "wotsit" keys
    println("b/wotsit")
default:
    break
}

      

I've tried the above and various other attempts to express this logic in a switch, but couldn't get it to work. So how could I do this in switch

(or is it something wrong)?

Reference Information:

Dictionaries are actually SwiftyJSON JSON

objects loaded from JSON data, and I want to infer that the "type" of an object these JSON structures represent from the keys they contain - unless they contain all the correct keys for a particular object. which they will not try to download as this type. I could add "type"

JSON for each structure and switch

based on that value, but I would prefer to automatically infer their type from the keys, as I am currently doing.

+3


source to share





All Articles