Sweeper Sweeper - 8 months ago 15
Swift Question

Is there something like a "reversible dictionary"?

I just want a data structure that acts similar to a

, but not only can I access the values using the keys, but also access the keys using the values.

So it would be something like this:

let dict: ReversibleDictionary<String, String> =
["1" : "one", "2" : "two", "3" : "three"]
dict.valueFromKey("1") // "one"
dict.keyFromValue("two") // "2"

Is there something like that built-in swift?

If there isn't, how can I create something like this myself?

I tried to create one using 2
s and use a linear search to find the corresponding values. But I think it's too inefficient to use a linear search, which is O(n) complexity. Accessing a dictionary should be O(1) complexity, right?


No, there is no built in data structure that does this.

But you could easily create your own data structure that consists of two dictionaries. When you add to this "ReversableDictionary" you just make sure to also add the inverse to the second dictionary.

Then internally you can perform the look up on the appropriate of the two dictionaries by implementing your own dict.valueFromKey() and dict.keyFromValue() methods

Look up should be O(1) at the expense of using twice as much storage.