如何在Swift中从hashValue实现哈希(到:)?

如何在Swift中从hashValue实现哈希(到:)?,swift,hashable,Swift,Hashable,我不太清楚如何处理编译器发出的弃用警告,即不要使用hashValue,而是实现hash(into:) “Hashable.hashValue”作为协议要求不推荐使用;符合 通过实现“hash(into:)”将“MenuItem”键入为“Hashable” 下面是一个例子: func hash(into hasher: inout Hasher) { switch self { case .mention: hasher.combine(-1) case .hashtag:

我不太清楚如何处理编译器发出的弃用警告,即不要使用
hashValue
,而是实现
hash(into:)

“Hashable.hashValue”作为协议要求不推荐使用;符合 通过实现“hash(into:)”将“MenuItem”键入为“Hashable”

下面是一个例子:

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
    }
}
我有这个结构,可以定制羊皮纸()的
PagingItem

<代码>导入基础 ///菜单的分页项。 结构菜单项:分页项,可散列,可比较{ let索引:Int 标题:字符串 让菜单:菜单 var hashValue:Int{ 返回index.hashValue&+title.hashValue } func散列(放入散列程序:inout散列程序){ //帮帮忙? } 静态函数==(左:菜单项,右:菜单项)->Bool{ 返回lhs.index==rhs.index&&lhs.title==rhs.title } 静态函数布尔{ 返回左侧索引<右侧索引 } }
您只需使用
散列器即可。将
与要用于散列的值组合起来调用它:

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)
}
可能有用:。
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)
}