swifthashable

How to Implement hash(into:) from hashValue in Swift?


I don't quite have an idea on what to do with the deprecation warning from the compiler to not use hashValue and instead implement hash(into:).

'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'MenuItem' to 'Hashable' by implementing 'hash(into:)' instead

The answer from Swift: 'Hashable.hashValue' is deprecated as a protocol requirement; has this example:

func hash(into hasher: inout Hasher) {
    switch self {
    case .mention: hasher.combine(-1)
    case .hashtag: hasher.combine(-2)
    case .url: hasher.combine(-3)
    case .custom(let regex): hasher.combine(regex) // assuming regex is a string, that already conforms to hashable
    }
}

And I do have this struct, to customise PagingItem of Parchment (https://github.com/rechsteiner/Parchment).

import Foundation

/// The PagingItem for Menus.
struct MenuItem: PagingItem, Hashable, Comparable {
    let index: Int
    let title: String
    let menus: Menus

    var hashValue: Int {
        return index.hashValue &+ title.hashValue
    }

    func hash(into hasher: inout Hasher) {
        // Help here?
    }

    static func ==(lhs: MenuItem, rhs: MenuItem) -> Bool {
        return lhs.index == rhs.index && lhs.title == rhs.title
    }

    static func <(lhs: MenuItem, rhs: MenuItem) -> Bool {
        return lhs.index < rhs.index
    }
}

Solution

  • You can simply use hasher.combine and call it with the values you want to use for hashing:

    func hash(into hasher: inout Hasher) {
        hasher.combine(index)
        hasher.combine(title)
    }