【问题标题】:will hasher.combine(self) cause trouble while using collections?hasher.combine(self) 会在使用集合时造成麻烦吗?
【发布时间】:2019-12-17 23:01:23
【问题描述】:

使用hash(into:) 的这种实现会导致问题,尤其是使用集合和数组吗?:

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

【问题讨论】:

  • 你为什么要散列self?这个想法是将您的属性散列在一起以创建 Hashable 的散列值。您能否提供一些上下文来说明为什么要这样做?
  • 如果计算机知道散列self 的含义,那么hash(into:) 方法将毫无用处。事实上,该方法的存在是为了定义散列 self 的确切含义。

标签: arrays swift hashable


【解决方案1】:

我很确定hasher.combine(self) 要么无法编译,要么导致无限循环。

hasher.combine() 看到给定的类型时,它会查找对象hash(into:) 函数,该函数将调用具有相同类型的hasher.combine(),依此类推。

你应该做的是

func hash(into hasher: inout Hasher) {
    hasher.combine(property1)
    hasher.combine(prop2)
    //...
    //...
    //...
    //...
    //...
    //...
    //until you have written a line to combine every property you want to hash
}

如果您有任何问题,请告诉我。

【讨论】:

  • 在 Xcode 版本 11.3 和 swift 5 上,它确实可以编译,但现在你解释了它是如何工作的,我不会使用它!谢谢!
【解决方案2】:

您的 Hasher 实现导致错误:

线程 1:EXC_BAD_ACCESS(代码=2,地址=0x7ffeeec79fe8)

这是使类型符合Hashable 协议的默认方式

/// A point in an x-y coordinate system.
struct GridPoint {
    var x: Int
    var y: Int
}

extension GridPoint: Hashable {
    static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(x)
        hasher.combine(y)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-11
    • 2012-08-25
    • 2015-09-17
    • 1970-01-01
    • 2011-07-10
    • 2016-07-16
    • 2022-07-22
    相关资源
    最近更新 更多