carlastar0 carlastar0 - 5 months ago 9
Swift Question

Access a key in a dictionary the value in swift

I am trying to access the key of a using it's value but, doesn't matter how much research I've done, I can't find the answer. Is there a way to do this? If so, how?

This is what I would like to happen:

myDictionary = [String: Int]()
myDictionary = [key: value]
label.text == myDictionary[value]
//label.text = key

Thanks for the help :)


There isn't a built-in way to do that. Dictionaries use their keys as hashes to store values in memory. So key is related to the memory location of value. But there isn't a relationship the other way from value to key. Also, while there can be only one value for a given key, there can be many keys with the same value. So you could end up with a situation where are searching for the key that matches a certain value... and there are multiple possible answers!

If you are sure that values in your dictionary are unique, you can enumerate all key/values in the dictionary and return the key when you find a value that matches the one you are testing for.

Here's an example of how to do that, implemented as an extension on Dictionary:

extension Dictionary {
    func keyForValue<T:Equatable>(searchValue:T) -> Key? {
        for (key, value) in self {
            if let value = value as? T where value == searchValue {
                return key
        return nil

let dictionary = [123534 : "Soup", 857372 : "Lasagna", 736428 : "Cookies"]
print(dictionary.keyForValue("Lasagna")!) //prints 857372

Not that this extension method only accepts a search value that is Equatable, so it can be compared to the values in the dictionary. It also has to be an optional return type, because there may not be a matching value in the dictionary.