作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的 iOS 项目一直面临以下问题(这只是一个警告)。
'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'ActiveType' to 'Hashable' by implementing 'hash(into:)' instead
源代码:
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:)”,但我不知道如何实现?
引用: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/55484437/
我是一名优秀的程序员,十分优秀!