首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift 5.0 "Set“允许重复值

问Swift 5.0 "Set“允许重复值
EN

Stack Overflow用户
提问于 2019-07-09 13:38:42
回答 1查看 530关注 0票数 3

在Swift5.0Playground中,我在CGPoint上试验了一些扩展,在哈希和相等方面,它将点视为整数值。

令我惊讶的是,即使在CGPoint上覆盖了hash()和==之后,一组CGPoints仍然保持着类似的值作为独立点,即使两个元素应该已经冲突并且只保留了一个。您是否需要在CGPoint上重写其他方法才能使此功能按预期工作?

附注:在实践中最好不要这样做,因为它可能会影响系统,最好提供某种类型的包装器来管理平等。但我想知道为什么这不起作用。

游乐场内容以及执行后给出的结果:

代码语言:javascript
复制
// 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-09 14:15:11

rmaddy和Martin R发现了这个问题,但这里的答案是:Set没有使用您的==函数。它使用在标准库中定义的==函数,因为Set是在标准库中定义的。您可以通过调用print作为您的==函数来证明这一点。当您将一个点插入到Set中时,您将看到您的print没有运行。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56945958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档