WeakObject
adopts Hashable
protocol.
public struct WeakObject {
public weak var object: AnyObject?
public init(_ object: AnyObject? = nil) {
self.object = object
}
}
extension WeakObject:Hashable{
public static func == (lhs: WeakObject, rhs: WeakObject) -> Bool {
return lhs.object === rhs.object
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.object?.hash)
}
}
class C1{
var c:Int?
}
Then I created a set.
var c1:C1? = C1()
var c2:C1? = C1()
var bn1 = WeakObject(c1)
var bn2 = WeakObject(c2)
var set:Set<WeakObject> = [bn1,bn2]
// assume
// bn1.hashValue == A
// bn2.hashValue == B
// WeakObject(nil) == N
Then I set nil
to property object
:
c1 = nil
c2 = nil
// now
// WeakObject(nil).hashValue == N
// bn1.hashValue == N
// bn2.hashValue == N
But when I remove Element (or use subtract)
set.remove(BNWeakObject(nil))
// I expect the set will be Empty
// but
print(set.isEmpty)
// false