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

"哈沙布尔.hashValue作为协议要求被弃用;通过实现"hash(into:)"将类型"ActiveType"与"Hashable"一致

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

最好(对于enum和struct)删除custom 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相关问答推荐

如何在DATE()中进行比较

如何强制创建新的UIViewControllerRenatable|更新Make UIViewController上的视图

解码器是否需要具有密钥的外部数据表示?

我需要一些关于 SwiftUI 动画的帮助

如何判断设备是否为 Vision Pro - Xcode 15 Beta 4

OSX 中的 Popover 无法确定透明度

如何在 AppDelegate for Cocoa macOS 中创建 mainMenu 和菜单项?

快速更改tableView中的数据

如何从数据中读取以空结尾的字符串?

LeetCode 249. 分组移位字符串

为什么 SwiftUI 不在工具栏菜单中反映 @State 属性值?

SwiftUI:异步网络请求后@State 值不更新

持久化字符串列表属性 RealmSwift

在 SwiftUI 中操作绑定变量

Vapor - 流利的,将对象保存到 PostgreSQL

Swift 2.0 方法不能标记为@objc,因为参数的类型不能在 Objective-C 中表示

在运行时访问 UIView 宽度

使 struct 可散列?

如何从一个可观察的数组创建一个可观察的数组?

强制打开已在同一行代码中 Select 性访问的变量是否安全?