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
}
}
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.
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.
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.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With