我认为这是一个NSObject
问题.
class MYUserNSObject: NSObject { dynamic var fullName: String init(fullName: String) { self.fullName = fullName super.init() } } func ==(left: MYUserNSObject, right: MYUserNSObject) -> Bool { return left.fullName == right.fullName } let objectUsers = [MYUserNSObject(fullName: "a"), MYUserNSObject(fullName: "b")] let objectResult = objectUsers.contains(MYUserNSObject(fullName: "a")) print("\(result)")
打印错误.
class MYUserSwift: Equatable { var fullName: String init(fullName: String) { self.fullName = fullName } } func ==(left: MYUserSwift, right: MYUserSwift) -> Bool { return left.fullName == right.fullName } let swiftUsers = [MYUserSwift(fullName: "a"), MYUserSwift(fullName: "b")] let swiftResult = swiftUsers.contains(MYUserSwift(fullName: "a")) print("\(swiftResult)")
打印真实.
最后,通过添加-isEqual:
,我修复了这个问题.
class MYUserNSObject: NSObject { dynamic var fullName: String init(fullName: String) { self.fullName = fullName super.init() } override func isEqual(object: AnyObject?) -> Bool { guard let user = object as? MYUserNSObject else { return false } return self == user } } func ==(left: MYUserNSObject, right: MYUserNSObject) -> Bool { return left.fullName == right.fullName } let objectUsers = [MYUserNSObject(fullName: "a"), MYUserNSObject(fullName: "b")] let objectResult = objectUsers.contains(MYUserNSObject(fullName: "a")) print("\(objectResult)")
打印真实.
针对Swift 4.0进行了更新
class MYUserNSObject: NSObject { @objc var fullName: String init(fullName: String) { self.fullName = fullName super.init() } override func isEqual(_ object: Any?) -> Bool { guard let user = object as? MYUserNSObject else { return false } return self.fullName == user.fullName } } let objectUsers = [MYUserNSObject(fullName: "a"), MYUserNSObject(fullName: "b")] let objectResult = objectUsers.contains(MYUserNSObject(fullName: "a")) print("\(objectResult)")
打印真实.
注意:不再需要==(left:right:)
功能.
let success = MYUserNSObject(fullName: "a") == objectUsers[0] print("success should be true: \(success)") let failure = MYUserNSObject(fullName: "a") == objectUsers[1] print("failure should be false: \(failure)")