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

How to conform to the Hashable protocol

Written by 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.

Get the ultimate experience

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

Click here to visit the Hacking with Swift store >>