In Cocoa Programming for OS X (5th ed.) you describe a Swift dictionary as “an unordered collection of Key-Value pairs”; you also state that the keys must be hashable to make sure they are unique. I cannot find a satisfactory explanation on the web for the meaning of “hashable” and why it guarantees uniqueness. All the explanations seem to rely on the fact that one already knows e.g. 'a collection is hashable if it can be hashed!!!. Can you provide an explanation or a reference please?

hashable in rough terms: if something is hashable, you can get an integer number out of it, which you can then use to index an array, usually after computing its remainder when divided by the size of the array.

OK, after reading considerably about hash tables and whatnot, I think I understand. Thanks for that concise reply.

I suppose that fundamentally my problem with the original statement in the book is “so what”. How does that affect me , the Swift programmer?
For instance, in Swift programming using a dictionary, is each entry checked by a built in hash function as it is entered to ensure it is hashable or does the coder have to do this explicitly?

For fundamental data types, such as numerics and strings, you don’t have to worry about the hashability requirement. But if you had a data type that does not conform to the Hashable protocol, then you would need to worry about it in order to use instances of that type as dictionary keys.

Excellent, thanks.

As an aside, you probably noticed that Apple’s spell checking auto correct cannot cope with “hashable” and insists on “washable”. What does it know that we do not?

I think, based on the usage, that “hashable” means “can be hashed” which is a shortened wording for “can be passed to a hash function successfully”. What then is a hash function?



It’s interesting reading on both subjects, if you have the time.