当前位置:  开发笔记 > IOS > 正文

Swift Array.contains()不调用PFUser子类的Equatable函数

如何解决《SwiftArray.contains()不调用PFUser子类的Equatable函数》经验,为你挑选了1个好方法。



1> Jeffery Thom..:

我认为这是一个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)")


是的,似乎Array.contains()特别为NSObject子类调用`-isEquals:`方法.谢谢.
推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有