ios - 子类化 MKAnnotation 导致 Set 集合不起作用
问题描述
我刚刚发现Set
typeMKAnnotation
没有按预期工作。
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
解决方案
推荐阅读
- javascript - 如何隐藏 Google API 密钥并仍然使用它
- apache-camel - 我在 apache camel 中处理 onException(真)的设计有问题
- android - 确定可用的生物识别硬件类型 Android
- python - Python - 使用 Plotly,有没有办法在放大气泡图时显示文本标签?
- java - JScrollPane 中一个位于另一个下方的按钮列表
- javascript - Web 组件转换发生得太晚
- html - `target="_blank"`和右键单击+`在新选项卡中打开链接`之间的Chrome差异
- swift - 相同的约束不同的结果
- sql - 应用程序的数据库结构向用户显示一次随机项目
- javascript - Windows:将 Webrtc 流提供给虚拟驱动程序