Swift Dictionary Get Key for Values

func findKeyForValue(value: String, dictionary: [String: [String]]) ->String?
{
    for (key, array) in dictionary
    {
        if (array.contains(value))
        {
            return key
        }
    }

    return nil
}

Call the above function which will return an optional String?

let drinks = ["Soft Drinks": ["Cocoa-Cola", "Mountain Dew", "Sprite"],
        "Juice" :["Orange", "Apple", "Grape"]]

print(self.findKeyForValue("Orange", dictionary: drinks))

This function will return only the first key of the array which has the value passed.


In Swift 2.0 you can filter the dictionary and then map the result to an array.

let keys = drinks.filter {
    return $0.1.contains("Orange")
}.map {
    return $0.0
}

The result will be an array of String object representing the matching keys.


Enumerate through all the dictionary entries and test each value list for the value you want and accumulate the keys where the value is present.

Example, finds all drinks that include the desired value in a list:

let drinks = [
    "Soft Drinks": ["Orange", "Cocoa-Cola", "Mountain Dew", "Sprite"],
    "Juice" :["Apple", "Grape"]
]

let value = "Orange"

var keys = [String]()
for (key, list) in drinks {
    if (list.contains(value)) {
        keys.append(key)
    }
}

print("keys: \(keys)")

keys: ["Soft Drinks"]

Tags:

Ios

Swift

Swift2