gpt4 book ai didi

swift - 如何实现散列(到 :) from hashValue in Swift?

转载 作者:搜寻专家 更新时间:2023-10-31 21:56:01 24 4
gpt4 key购买 nike

我不太清楚如何处理编译器发出的不使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com