My code looks like this:
var dict = ["a": 1, "b": 2]
var valueInDict = 1
My question is whether it's possible to access the key, in this case "a", using only the value.
My code looks like this:
var dict = ["a": 1, "b": 2]
var valueInDict = 1
My question is whether it's possible to access the key, in this case "a", using only the value.
Use the fact that Dictionary values and keys properties are documented to have the same order:
if let index = dict.values.indexOf(valueInDict) {
let key = dict.keys[index]
print(key)
}
It is not possible to get the key by its value, because multiple keys can have the same value. For example, if you make a dictionary like this
let dict = [
"a" : 7
, "b" : 3
, "c" : 11
, "d" : 7
, "e" : 3
, "f" : 11
]
and try to find the key of value 7
, there would be two such keys - "a"
and "d"
.
If you would like to find all keys that map to a specific value, you can iterate the dictionary like this:
let search = 7
let keys = dict // This is a [String:int] dictionary
.filter { (k, v) -> Bool in v == search }
.map { (k, v) -> String in k }
This produces keys of all entries that have the search
value, or an empty array when the search
value is not present in the dictionary.