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"
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With