gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:35:33 26 4
gpt4 key购买 nike

我刚刚发现 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com