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

标签 swift hashable swift5

我的 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/55484437/

相关文章:

ios - Swift:将弹出窗口中的数据添加到结构中并在 TableView 中显示

ios - 在 iOS 中不使用颜色的垂直 Alpha 渐变

ios - 使 swift 协议(protocol)符合 Hashable

swift 5 : How to make a Set containing Class Types (for NSXPCInterface)

ios - 快速获取用户的联系人电话号码

ios - 调整约束高度后,Swift 约束无法移回屏幕底部

swift - 我们是否应该始终在 Swift 中的闭包内使用 [unowned self]

ios - 从 FMDB 数据库中获取数据

objective-c - 使用 ErrorType 时框架 header 中缺少 Swift 方法

Swift:具有字典属性的可哈希结构