作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我不太清楚如何处理编译器发出的不使用 hashValue
而是实现 hash(into:)
的弃用警告。
'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'MenuItem' to 'Hashable' by implementing 'hash(into:)' instead
答案来自Swift: 'Hashable.hashValue' is deprecated as a protocol requirement;有这个例子:
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)
}
关于swift - 如何实现散列(到 :) from hashValue in Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687214/
我是一名优秀的程序员,十分优秀!