0

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.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Shiv Bhatia
  • 351
  • 1
  • 3
  • 10
  • When you have a problem like this one, the first step is to check the available tools, e.g. public API, which would show you the `allKeys` property of `NSDictionary`. This isn't an optimal way to solve the problem in general, for a better result you might want to consider implementing a storage that will better suit your needs. – A-Live Nov 15 '15 at 12:32

2 Answers2

10

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)
}
Gwendal Roué
  • 3,949
  • 15
  • 34
8

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523