ios - 子类化 MKAnnotation 导致 Set 集合不起作用

标签 ios swift inheritance set mapkit

我刚刚发现 MKAnnotation 类型的 Set 没有按预期工作。

class MyAnnotation: MKPointAnnotation {
    let id: String

    init(_ id: String) {
        self.id = id
    }

    override var hash: Int {
        return id.hash
    }

    static func ==(lhs: MyAnnotation, rhs: MyAnnotation) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

let m1 = MyAnnotation("1")
let m2 = MyAnnotation("2")
let n1 = MyAnnotation("1")
let n2 = MyAnnotation("2")

m1.hashValue //918
n1.hashValue //918

m2.hashValue //921
n2.hashValue //921

if m1 == n1 && m2 == n2 {
    print(true)
}
// prints true

let s1 = Set(arrayLiteral: m1, m2)
let s2 = Set(arrayLiteral: n1, n2)

let i = s1.intersection(s2)
// empty

即使哈希相同,m 和 n 的交集也是空的。请与下面的示例进行比较:

class MyAnnotation: Hashable, Equatable {
    let id: String

    init(_ id: String) {
        self.id = id
    }

    var hashValue: Int {
        return id.hash
   }

    static func ==(lhs: MyAnnotation, rhs: MyAnnotation) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

let m1 = MyAnnotation("1")
let m2 = MyAnnotation("2")
let n1 = MyAnnotation("1")
let n2 = MyAnnotation("2")

m1.hashValue //918
n1.hashValue //918

m2.hashValue //921
n2.hashValue //921

if m1 == n1 && m2 == n2 {
    print(true)
}
// prints true

let s1 = Set(arrayLiteral: m1, m2)
let s2 = Set(arrayLiteral: n1, n2)

let i = s1.intersection(s2)
// {{id "1"}, {id "2"}}

m 和 n 的交集符合预期。

是不是很奇怪?也许中间有一些我不知道也不明白的东西。

Xcode 10.1

最佳答案

在第一个代码中,您没有使用 Equatable 协议(protocol),但在第二个代码中您使用了 Equatable 协议(protocol),因此它可以正常工作。

Equatable 协议(protocol)用于比较。您可以引用以下链接了解更多信息:

https://useyourloaf.com/blog/swift-equatable-and-comparable/

关于ios - 子类化 MKAnnotation 导致 Set 集合不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53268268/

相关文章:

ios - 观察来自 ViewController 的通知

java - 类已在 null 中定义

javascript - 为什么在扩展对象时使用 Object.create 作为原型(prototype)?

java - 创建另一个子类java的构造函数

ios - UIActivityViewController 在共享到消息时删除冗余空间

ios - 属性另一个UIViewController为null

objective-c - 如何在单元测试中访问 NSDocumentDirectory (OCUnit)

swift - 缺少 xcode 8.1 调试符号

swift - 无法在 ListView 中使用已解析的数据

swift - 如何验证属性的传入数据?