【问题标题】:How to Implement hash(into:) from hashValue in Swift?如何在 Swift 中从 hashValue 实现 hash(into:)?
【发布时间】:2019-09-05 07:39:59
【问题描述】:

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

'Hashable.hashValue' 作为协议要求已被弃用;符合 通过实现 'hash(into:)' 将 'MenuItem' 键入到 'Hashable'

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 的 PagingItem (https://github.com/rechsteiner/Parchment)。

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

【问题讨论】:

标签: swift hashable


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    hashValue 创建有两个现代选项。

    func hash(into hasher: inout Hasher) {
      hasher.combine(foo)
      hasher.combine(bar)
    }
    
    // or
    
    // which is more robust as you refer to real properties of your type
    func hash(into hasher: inout Hasher) {
      foo.hash(into: &hasher)
      bar.hash(into: &hasher)
    }
    

    【讨论】:

    • 请注意:combine(:) 方法只是一种方便的操作,它接受一个 Hashable 值,例如整数或字符串。在幕后,这个 combine(:) 方法调用 hash(into:) 方法将其值混合到 Hasher 状态中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2019-01-12
    • 2015-11-30
    • 2014-09-07
    相关资源
    最近更新 更多