将我们的代码库升级到
Swift2后,我遇到了异常的问题. Set不是预期的减法或联合.
class A: NSObject { let h: Int init(h: Int) { self.h = h } override var hashValue: Int { return h } } func ==(lhs: A,rhs: A) -> Bool { return lhs.hashValue == rhs.hashValue } let a = A(h: 1) let b = A(h: 1) var sa = Set([a]) let sb = Set([b]) sa.subtract(sb).count // Swift1.2 prints 0,Swift 2 prints 1 sa.contains(a) // Swift1.2 true,Swift 2 true sa.contains(b) // Swift1.2 true,Swift 2 false
我玩了你的代码了一下.我能够通过不再继承NSObject来使其工作,而是符合Hashable协议:
原文链接:https://www.f2er.com/swift/319243.htmlclass A: Hashable { let h: Int init(h: Int) { self.h = h } var hashValue: Int { return h } } func ==(lhs: A,Swift 2 false a.hashValue == b.hashValue
当您从NSObject继承时,您的==重载实际上并未执行.如果你想让它与NSObject一起使用,你必须覆盖isEquals:
override func isEqual(object: AnyObject?) -> Bool { if let object = object as? A { return object.h == self.h } else { return false } }