Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

hashable

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
    }
}
like image 274
Glenn Posadas Avatar asked Apr 15 '19 10:04

Glenn Posadas


People also ask

What is hashValue in Swift?

The way it works is that Hashable exposes a hashValue property (now Hasher in Swift 4.2), which is an Int that represents a not-guaranteed-but-hopefully-most-of-the-times unique number that represents the contents of that type.

What is Hasher Swift?

Within the execution of a Swift program, Hasher guarantees that finalizing it will always produce the same hash value as long as it is fed the exact same sequence of bytes.

How do you make a struct conform to hashable?

To add Hashable conformance, provide an == operator function and implement the hash(into:) method. The hash(into:) method in this example feeds the grid point's x and y properties into the provided hasher.

How do you make something hashable in Swift?

Starting with Swift 4.1 the easiest way to make our type hashable is to have the compiler automatically synthesise conformance for us (see How To Get Equatable And Hashable For Free). We just feed each of the essential components of our type into the combine function of the hasher provided by the standard library.


1 Answers

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)
}
like image 176
Dávid Pásztor Avatar answered Oct 04 '22 03:10

Dávid Pásztor