Kru*_*nal 21 hashable swift swift5
我的iOS项目一直面临以下问题(这只是警告)。
“ Hashable.hashValue”已作为协议要求弃用;通过实现'hash(into :)'来使类型'ActiveType'与'Hashable'一致
源代码:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
有更好的解决方案吗?警告本身建议我实施“哈希(into :)”,但我不知道怎么做?
参考:ActiveLabel
Ric*_*zio 42
如警告所述,现在您应该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
}
}
Run Code Online (Sandbox Code Playgroud)
提示:您不需要使枚举显式符合,Equatable因为会对其进行Hashable扩展。
小智 11
要实现该hash(into:)功能,请执行以下操作:
public class JSONNull: Codable, Hashable {
public var hashValue: Int {
return 0
}
}
Run Code Online (Sandbox Code Playgroud)
应该更新如下:
public class JSONNull: Codable, Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(0)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6903 次 |
| 最近记录: |