Swift:“Hashable.hashValue"作为协议要求已被弃用; [英] Swift: 'Hashable.hashValue' is deprecated as a protocol requirement;
问题描述
我的 iOS 项目一直面临以下问题(这只是一个警告).
I've been facing following issue (it's just a warning) with my iOS project.
'Hashable.hashValue' 作为协议要求被弃用;通过实现 'hash(into:)' 来使类型 'ActiveType' 符合 'Hashable'
'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'ActiveType' to 'Hashable' by implementing 'hash(into:)' instead
- Xcode 10.2
- 斯威夫特 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
}
}
}
有更好的解决方案吗?警告本身建议我实施 'hash(into:)',但我不知道,如何?
Any better solution? The warning itself suggesting me to implement 'hash(into:)' but I don't know, how?
参考:ActiveLabel
推荐答案
正如警告所说,现在您应该改为实现 hash(into:)
函数.
As the warning says, now you should implement the hash(into:)
function 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
}
}
删除自定义 hash(into:)
实现(除非您需要特定实现)会更好(在枚举和结构的情况下),因为编译器会自动为您合成它.
It would be even better (in case of enums and struct) to remove the custom hash(into:)
implementation (unless you need a specific implementation) as the compiler will automatically synthesize it for you.
只要让你的枚举符合它:
Just make your enum conforming to it:
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"作为协议要求已被弃用;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!