How to Make Struct Hashable in Swift 5

by

We have used struct for purposes like small-scale copiable entity representing common-kinds-of-data. What if we want to make our custom struct model equatable? We want our struct to be analysed for basic equality of comparison. What if we have an array of struct and we want to perform some operation to array like sorting or create an unique array by removing duplicate structs.

We have seen this error shown when we try to perform such operation of comparison:



Type ‘CustomStruct’ does not conform to protocol ‘Hashable’

According to Apple’s documentation:

You can use any type that conforms to the Hashable protocol in a set or as a dictionary key. To use your own custom type in a set or as the key type of a dictionary, add Hashable conformance to your type. The Hashable protocol inherits from the Equatable protocol, so you must also satisfy that protocol’s requirements.


struct Message : CustomStringConvertible, Hashable {
    var description: String{
        return title ?? "No title provided."
    }
    
    var title:String?
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(title)
    }
    
    static func == (lhs: Message, rhs: Message) -> Bool {
        return lhs.title == rhs.title && lhs.title == rhs.title
    }
}

hash(into:)

Implement this method to conform to the Hashable protocol. The components used for hashing must be the same as the components compared in your type’s == operator implementation. Call hasher.combine(_:) with each of these components.

Documentation says that we have to use same component for hashing and equality comparison operator. In our example above our component being used is title. We want our comparison to be happening based on title property. Operations like removing duplicates from a collection to get unique values of struct can be achieved now.

More Articles

Recommended posts