在Swift5.0Playground中,我在CGPoint上试验了一些扩展,在哈希和相等方面,它将点视为整数值。
令我惊讶的是,即使在CGPoint上覆盖了hash()和==之后,一组CGPoints仍然保持着类似的值作为独立点,即使两个元素应该已经冲突并且只保留了一个。您是否需要在CGPoint上重写其他方法才能使此功能按预期工作?
附注:在实践中最好不要这样做,因为它可能会影响系统,最好提供某种类型的包装器来管理平等。但我想知道为什么这不起作用。
游乐场内容以及执行后给出的结果:
// Extension to treat points as integer values (not reccomended approach)
extension CGPoint : Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(Int(x))
hasher.combine(Int(y))
}
static public func == (lhs: CGPoint, rhs: CGPoint) -> Bool {
return Int(lhs.x) == Int(rhs.x) && Int(lhs.y) == Int(rhs.y)
}
}
var pSet : Set<CGPoint> = []
let p1 = CGPoint.zero
let p2 = CGPoint(x: 20.1, y: 30)
let p3 = CGPoint(x:20, y: 30)
pSet.insert(p1) // inserted true
pSet.insert(p2) // inserted true
pSet.insert(p3) // inserted true(!), should be false
p2 == p3 // true
pSet.count // 3(!), should be two
p2.hashValue // Same as p3
p3.hashValue // Same as p2
pSet // shows all three values, all points defined, should be two values only发布于 2019-07-09 14:15:11
rmaddy和Martin R发现了这个问题,但这里的答案是:Set没有使用您的==函数。它使用在标准库中定义的==函数,因为Set是在标准库中定义的。您可以通过调用print作为您的==函数来证明这一点。当您将一个点插入到Set中时,您将看到您的print没有运行。
https://stackoverflow.com/questions/56945958
复制相似问题