gpt4 book ai didi

Swift: 'Hashable.hashValue' 作为协议(protocol)要求已弃用;

转载 作者:IT王子 更新时间:2023-10-29 05:16:48 26 4
gpt4 key购买 nike

我的 iOS 项目一直面临以下问题(这只是一个警告)。

'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'ActiveType' to 'Hashable' by implementing 'hash(into:)' instead

  • Xcode 10.2
  • swift 5

源代码:

public enum ActiveType {
case mention
case hashtag
case url
case custom(pattern: String)

var pattern: String {
switch self {
case .mention: return RegexParser.mentionPattern
case .hashtag: return RegexParser.hashtagPattern
case .url: return RegexParser.urlPattern
case .custom(let regex): return regex
}
}
}

extension ActiveType: Hashable, Equatable {
public var hashValue: Int {
switch self {
case .mention: return -1
case .hashtag: return -2
case .url: return -3
case .custom(let regex): return regex.hashValue
}
}
}

enter image description here

有更好的解决方案吗?警告本身建议我实现“hash(into:)”,但我不知道如何实现?

引用:ActiveLabel

最佳答案

正如警告所说,现在您应该改为实现 hash(into:) 函数。

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
}
}

移除自定义hash(into:) 实现(除非您需要特定的实现)会更好(在枚举和结构的情况下),因为编译器会自动为您合成它.

只需让您的枚举符合它:

public enum ActiveType: Hashable {
case mention
case hashtag
case url
case custom(pattern: String)

var pattern: String {
switch self {
case .mention: return RegexParser.mentionPattern
case .hashtag: return RegexParser.hashtagPattern
case .url: return RegexParser.urlPattern
case .custom(let regex): return regex
}
}
}

关于Swift: 'Hashable.hashValue' 作为协议(protocol)要求已弃用;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55395207/

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