如何在Swift中从hashValue实现hash(into :)?

时间:2019-04-15 10:30:25

标签: swift hashable

对于从编译器中弃用警告而不使用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
    }
}

我确实有这个结构,可以自定义羊皮纸(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
    }
}

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

hashValue的创建有两种现代选择。

func hash(into hasher: input 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: input Hasher) {
  foo.hash(into: &hasher)
  bar.hash(into: &hasher)
}