swift - 如何实现散列(到 :) from hashValue in Swift?

标签 swift hashable

我不太清楚如何处理编译器发出的不使用 hashValue 而是实现 hash(into:) 的弃用警告。

'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'MenuItem' to 'Hashable' by implementing 'hash(into:)' instead

答案来自Swift: 'Hashable.hashValue' is deprecated as a protocol requirement;有这个例子:

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

我确实有这个结构,用于自定义 Parchment (https://github.com/rechsteiner/Parchment) 的 PagingItem

import Foundation

/// The PagingItem for Menus.
struct MenuItem: PagingItem, Hashable, Comparable {
    let index: Int
    let title: String
    let menus: Menus

    var hashValue: Int {
        return index.hashValue &+ title.hashValue
    }

    func hash(into hasher: inout Hasher) {
        // Help here?
    }

    static func ==(lhs: MenuItem, rhs: MenuItem) -> Bool {
        return lhs.index == rhs.index && lhs.title == rhs.title
    }

    static func <(lhs: MenuItem, rhs: MenuItem) -> Bool {
        return lhs.index < rhs.index
    }
}

最佳答案

您可以简单地使用 hasher.combine 并使用您想要用于散列的值调用它:

func hash(into hasher: inout Hasher) {
    hasher.combine(index)
    hasher.combine(title)
}

关于swift - 如何实现散列(到 :) from hashValue in Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687214/

相关文章:

swift - UIAlertController 按钮单击导航到 NavigationController 的第一个 ViewController

swift - 快速点击栏按钮上的退出键盘

swift - 自身,协议(protocol)扩展和非最终类

python - 使用带有字典参数的@functools.lru_cache

xcode - CFString 不符合 Hashable 协议(protocol)?

python - 与Python设置混淆两次添加相同的对象

ios - 如何在每天的特定时间发送 localNotification,即使那个时间已经过去了?

ios - 如何在 iOS Swift 3 中允许 CollectionViewCell 文本字段的所有字符均为大写字母且字符限制为 1?

Swift:如何使我的自定义结构 Node<T> 符合 Hashable?

swift - 为什么struct在转换为字典时需要符合Hashable以及Generic数组