[swift-evolution] [Draft] Hasher & HashVisitable

Karl Wagner razielim at gmail.com
Tue Mar 14 23:06:41 CDT 2017

> On 15 Mar 2017, at 01:10, Jaden Geller via swift-evolution <swift-evolution at swift.org> wrote:
> If this were desired, an associated type would not be sufficient. Perhaps `Dictionary` only supports keys where `Hash == Int`. Then any type that might key a dictionary must use `Int` as it’s hash type. It wouldn’t be possible to define a second implementation with `Int128` or any other types as the hash type since each type can only conform to a protocol once.
> Now, if we had generic protocols, this would be possible…
> extension Foo: Hashable<Int> { … }
> extension Foo: Hashable<Int128> { … }
> I’m not sure if that would even be a reasonable design though; I’m just pointing out that the associated type would be problematic.
> Cheers,
> Jaden Geller

I believe the associated type would be on the Hasher in that case (not the Hashee, which just feeds it bytes). So if the Hasher was a generic parameter on Dictionary with suitable default, its keys would all produce values of the same type anyway. The “hashValue” property could be defined as having to return a word-sized hash; if you override it and use your own “standard hasher” for a particular type, you would have to compact it in to an Int somehow.

The big problem with making Dictionary<K, V> in to Dictionary<K, V, H> is that from an API perspective, almost nobody who uses a Dictionary cares about the hashing function being used. We could solve this by allowing partially-bound generic types (e.g. Dictionary<K, V, _>) and either define a typealias, or formalise the notion of a private/optional generic type parameter which does not affect a type’s API and is never required to be specified. Alternatively, we could refactor Dictionary’s implementation as SecureDictionary<K, V, H> and keep Dictionary<K, V> as a wrapper (with the obvious caveat that your custom dictionaries won’t work with most other library code).

- Karl

More information about the swift-evolution mailing list