Hashable

minna zacharias
1 min readMay 30, 2021

As per the Apple documentation,

A type that can be hashed into a Hasher to produce an integer hash value.

A hash value is an Int value that’s the same for all objects that compare equally, such that if a == b, the hash value of a is equal to the hash value of b.

All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and can be used as set value types or dictionary key types. Enumeration case values without associated values are also hashable by default.

Your own custom types can be hashable as well. When you define an enumeration without associated values, it gains Hashable conformance automatically, and you can add Hashable conformance to your other custom types by implementing the hash(into:) method. For structs whose stored properties are all Hashable, and for enum types that have all-Hashable associated values, the compiler is able to provide an implementation of hash(into:) automatically.

Swift provides a synthesized implementation of Hashable for the following kinds of custom types:

-Structures that have only stored properties that conform to the Hashable protocol

-Enumerations that have only associated types that conform to the Hashable protocol

-Enumerations that have no associated types

To receive a synthesized implementation of hash(into:), declare conformance to Hashable in the file that contains the original declaration, without implementing a hash(into:) method yourself.

--

--