NEW! Master Swift design patterns with my latest book! >>

How to conform to the Hashable protocol

Paul Hudson       @twostraws

As of Swift 4.1, conforming to the Hashable protocol is often just as easy as adding Hashable to your conformance list. However, if you have custom requirements, use properties that don’t all conform to Hashable, or need to support earlier Swift versions for some reason, it takes a little more work.

Here’s an example struct we can work with:

struct Person {
    var firstName: String
    var lastName: String

To make that conform to Hashable we need to provide a hashValue property that will return a unique, consistent number for each instance of the struct.

There are several ways you can do this, but the easiest thing is usually to use bitwise XOR (^) to combine hash values from each of your properties then perform an overflowing multiply (&*) with a prime constant.

For example:

struct Person: Hashable {
    var firstName: String
    var lastName: String

    var hashValue: Int {
        return firstName.hashValue ^ lastName.hashValue &* 16777619

The Hashable protocol inherits from Equatable, so you may also need to implement an == function such as this one:

static func ==(lhs: Person, rhs: Person) -> Bool {
    return lhs.firstName == rhs.firstName && lhs.firstName == rhs.lastName

It’s worth adding that if two objects compare as equal using == they should also generate the same hash value, but the reverse isn’t true – hash collisions can happen and that’s OK.

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Want to build macOS apps?

Hacking with macOS delivers 18 awesome projects that teach you macOS development in no time – take control of your desktop today!

Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>