如何从 Swift 中的 hashValue 实现 hash(into:)?
How to Implement hash(into:) from hashValue in Swift?
我不太清楚如何处理编译器发出的弃用警告,不使用 hashValue
而是实现 hash(into:)
.
'Hashable.hashValue' is deprecated as a protocol requirement; conform
type 'MenuItem' to 'Hashable' by implementing 'hash(into:)' instead
的答案有这个例子:
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
}
}
我确实有这个结构,可以自定义 Parchment (https://github.com/rechsteiner/Parchment) 的 PagingItem
。
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
}
}
您可以简单地使用 hasher.combine
并使用您想要用于散列的值调用它:
func hash(into hasher: inout Hasher) {
hasher.combine(index)
hasher.combine(title)
}
hashValue
创建有两个现代选项。
func hash(into hasher: inout Hasher) {
hasher.combine(foo)
hasher.combine(bar)
}
// or
// which is more robust as you refer to real properties of your type
func hash(into hasher: inout Hasher) {
foo.hash(into: &hasher)
bar.hash(into: &hasher)
}
我不太清楚如何处理编译器发出的弃用警告,不使用 hashValue
而是实现 hash(into:)
.
'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'MenuItem' to 'Hashable' by implementing 'hash(into:)' instead
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
}
}
我确实有这个结构,可以自定义 Parchment (https://github.com/rechsteiner/Parchment) 的 PagingItem
。
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
}
}
您可以简单地使用 hasher.combine
并使用您想要用于散列的值调用它:
func hash(into hasher: inout Hasher) {
hasher.combine(index)
hasher.combine(title)
}
hashValue
创建有两个现代选项。
func hash(into hasher: inout Hasher) {
hasher.combine(foo)
hasher.combine(bar)
}
// or
// which is more robust as you refer to real properties of your type
func hash(into hasher: inout Hasher) {
foo.hash(into: &hasher)
bar.hash(into: &hasher)
}