So, that is the basics of Hashable
for data types in Swift. It is just a means to distill a simple integer from a potentially complex data structure in order to allow for a fast path in certain kinds of algorithms and data structures, such as dictionaries and sets. And thanks to all of the knowledge we have built up previously, we can summarize the Hashable
protocol as simply a computed property on an equatable type that is well-defined. That’s all it is. And if you don’t fulfill that promise in your type, it will be very easy to write reasonable looking code that produces very unreasonable results.
So, we should all feel pretty comfortable with the Equatable
and Hashable
protocols now. We have gone deep into their theoretical foundations, and shown time and time again why the properties of “equivalence relations” and “well-definedness” must be upheld in order to write code that is easy to reason about. But there is one major part of the Swift programming language that we have purposely ignored each step of the way, and that is reference types.
Everything so far has used value types, and for good reason. Value types are just bags of data, and this is a concept that mathematics does very well with, which is where the root of all the concepts can be found.
But reference types throw a wrench in all of the wonderful mathematical properties we have explored. They are an amalgamation of data and behavior, and they can change their data over time all on their own. That seems quite complicated, and so how are we supposed to deal with equatability when it comes to reference types?
Well, let’s dive into that right now.