Member-only story
What Is Hashable in Swift?
A deep dive into the Hashable protocol and its broader background

When we learn the basic data types in Swift, the official documentation mentions the Hashable
protocol several times.
For example, a key in the Dictionary
data type needs to be Hashable
. For another example, the elements in the Set
data type need to be Hashable
, too. As shown below, the declarations for Dictionary and Set clearly specify such requirements:
@frozen struct Dictionary<Key, Value> where Key : Hashable@frozen struct Set<Element> where Element : Hashable
The documentation lists several Hashable
data types, including booleans, integers, and strings, so that they can be used as the keys for a Dictionary and as the elements for a Set.
However, it’s unclear to us what makes these data types Hashable
, and how we can make our own data types Hashable
.
If we step back, we may also wonder why we bother making certain data types Hashable
in the first place. Do they have particular advantages? We can ask many more questions on this topic.
In this article, I’m trying to provide an in-depth overview of the Hashable
protocol in Swift and its common use cases. Specifically, we’re going to address the following questions/topics.
- The general discussion of hashing.
- What’s the
Hashable
protocol in Swift? - How to make our custom type conform to the
Hashable
protocol.
Hashing: What and Why
When we talk about hash, many terms have been frequently used in various settings, including hash, hashing, hasher, hash code, hash value, hash table, and hash function.
Even if we are not familiar with all of these terms, we do use them a lot in various programming languages as well as our everyday life (e.g., password encryption), at least indirectly.
Basic concepts
Generally speaking, hashing is the process of applying an algorithm to convert a data item to a value. The data item can be as simple as an integer, a string, or as complex as an object with multiple properties.