平常,我们判断两个对象是否相等可以用==
示例:
class AA:NSObject {
let id:String
init(id:String) {
self.id = id
super.init();
}
}
let a1 = AA(id: "2")
let a2 = AA(id: "2")
结果:
a1 == a2
//结果:false,因为本来就是两个对象
这里重写
override func isEqual(_ object: Any?) -> Bool
class AA:NSObject {
let id:String
init(id:String) {
self.id = id
super.init();
}
override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? AA else {
return false
}
return id == other.id
}
}
结果
a1 == a2
//结果:true,因为我们让id相等成为其相等的条件
结论:
我们可以自由的定制两个对象相等的条件,只要重写
override func isEqual(_ object: Any?) -> Bool
重点来啦
class AA:NSObject {
let id:String
init(id:String) {
self.id = id
super.init();
}
override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? AA else {
return false
}
return id == other.id
}
}
let a0 = AA(id: "1")
let a1 = AA(id: "2")
let a2 = AA(id: "2")
let a3 = AA(id: "4")
var a:Set<AA> = [a0,a1]
var b:Set<AA> = [a2,a3]
let c = a.subtracting(b)
结果为:
c:[a0,a1]
为什么,a1不能移除,因为a1等于a2阿.
原因是,Set是用哈希表存的,哈希表里要找相同的对象,首先就要有相同的哈希值,再然后是isEqual.所以在AA里加override var hashValue: Int
class AA:NSObject {
let id:String
init(id:String) {
self.id = id
super.init();
}
override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? AA else {
return false
}
return id == other.id
}
override var hashValue: Int{
return Int(id)!
}
}
let c = a.subtracting(b)
结果为:
c:[a0]
网友评论