Как реализовать хэш (в :) из hashValue в Swift?

Я не совсем понимаю, что делать с предупреждением об устаревании от компилятора, чтобы не использовать hashValue и вместо этого реализовать hash(into:).

Hashable.hashValue устарел как требование протокола; согласовать тип MenuItem с Hashable, реализовав вместо этого hash (into :)

Ответ от Swift: Hashable.hashValue устарел как требование протокола; есть этот пример:

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

И у меня есть эта структура для настройки 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
    }
}

person Glenn Posadas    schedule 15.04.2019    source источник
comment


Ответы (2)


Вы можете просто использовать hasher.combine и вызывать его со значениями, которые хотите использовать для хеширования:

func hash(into hasher: inout Hasher) {
    hasher.combine(index)
    hasher.combine(title)
}
person Dávid Pásztor    schedule 15.04.2019

Есть два современных варианта создания 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)
}
person dimpiax    schedule 27.05.2020