Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Dictionary Get Key for Values

Tags:

ios

swift

swift2

I have a dictionary 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"
like image 225
Statik Avatar asked Sep 21 '15 10:09

Statik


People also ask

How do you check if a dictionary contains a key Swift?

Swift – Check if Specific Key is Present in Dictionary To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.

What is NSDictionary in Swift?

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

Is it possible to use a custom struct as a dictionary key Swift?

Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types. You can use your own custom types as dictionary keys by making them conform to the Hashable protocol.


1 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 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.

like image 139
abintom Avatar answered Nov 08 '22 15:11

abintom