Swift Dictionary Get key for values

I have a dictionary that is defined as:

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

How can I get the key for a given value.

 let key = (drinks as NSDictionary).allKeysForObject("Orange") as! String print(key) //Returns an empty Array. Should return "Juice" 
+7
ios swift swift2
source share
4 answers
 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 that 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 returns only the first key of the array that has the passed value.

+15
source share

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 objects representing the corresponding keys.

+8
source share

List all entries in the dictionary and check each list of values โ€‹โ€‹for the desired value and copy the keys in which the value is present.

Example, finds all drinks that include the desired value in the 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)") 

: [ "Soft drinks" ]

+2
source share

try this (fast):

 (dic as NSDictionary).allKeysForObject(<#T##anObject: AnyObject##AnyObject#>) 

he works for me

-2
source share

All Articles