首页 > 解决方案 > 子类化 MKAnnotation 导致 Set 集合不起作用

问题描述

我刚刚发现SettypeMKAnnotation没有按预期工作。

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's 和 n's 的交集符合预期。

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

Xcode 10.1

标签: iosswiftinheritancesetmapkit

解决方案



推荐阅读