🎉 End-of-year Sale! Save 25% when you subscribe today.

Back to Basics: Hashable References

Episode #299 • Oct 21, 2024 • Subscriber-Only

We’ve studied Equatable and Hashable, their laws, and saw how value types as simple bags of data easily conform via “structural” equality. What about reference types? Reference types are an amalgamation of data and behavior, and that data can be mutated in place at any time, so how can they reasonably conform to these protocols?

Collection
Equatable and Hashable
Back to Basics: Hashable References
Locked

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub

Introduction

Brandon

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.

Stephen

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.

Brandon

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.

Stephen

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.

Reference types


References

Downloads

Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 64 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing