-1

If I want to create a Dictionary<Key:Value>() it is required for the Key type object to the protocol Hashable. Why is that the case, how are Dictionaries implemented?

I mean I would understand that if the Key just needs to conform to the protocol of Equatable type, as the program will have to search for the related value, however, the extra var hashValue: Int that comes along with Hashable is a bit confusing

rahulg
  • 2,183
  • 3
  • 33
  • 47
  • 4
    Hint: a dictionary is a hash map. – rmaddy May 01 '18 at 14:27
  • This isn't a Swift question as much as it's a general programming question. By definition a dictionary is a data structure that uses keys' hashes to locate their values. – BallpointBen May 01 '18 at 14:41
  • @rmaddy makes lot more sense :-) Why do they call it a dictionary? Should call it a HashMap like Java – rahulg May 01 '18 at 14:43
  • 4
    @BallpointBen A dictionary (the general computing data structure, also known as an associative array) does not need to use a hash to look up the value, it's more general than that. A dictionary is a collection of key-value pairs that you can use to store and look up values by just having the appropriate key. The hash part is an optimization to provide faster lookup time by implementing the dictionary as a hash map. It could just as easily be a search tree-type structure. –  May 01 '18 at 14:50
  • 1
    And a "search tree-type structure" would require elements to be `Comparable` instead of `Hashable`. Each has its trade offs. OP: If you're looking for a associative datatype that uses `Equatable` keys, see [`DictionaryLiteral`](https://developer.apple.com/documentation/swift/dictionaryliteral), which is basically just a wrapper around `Array<(Key: Equatable, Value)>` – Alexander May 01 '18 at 15:30
  • “ Why do they call it a dictionary? Should call it a HashMap like Java” Dictionary is the proper name as they don’t have to guarantee using a hash map in the future. The hash map is an implementation detail best hidden from the name in this case. – oxygen Aug 04 '23 at 14:05

1 Answers1

1

Hashable keys make dictionary inserts and lookups more efficient, especially for large dictionaries.

If the key is not hashable, in order to find a particular key you have to (in the worst case) read and compare for equality all keys in the dictionary.

Hashable keys are naturally divided into buckets by their hash values, and to find a particular key you calculate its hash to determine the bucket it's in, then you only need to compare for equality keys that belong to the same bucket. If the hash function is chosen correctly and the number of elements in the dictionary is less than the maximum Int value, you have a pretty good chance to have only one key per bucket, thus making the lookup as efficient as O(1).

There is more information in this related question.

mustaccio
  • 18,234
  • 16
  • 48
  • 57