Swift上的数组比较没有按预期工作

时间:2016-05-13 12:02:26

标签: ios arrays swift comparison

我有一个班级import SwiftyJSON class Email: NSObject { required init?(JSON jsonObject: AnyObject) { let emailJsonObject = JSON(jsonObject) self.email = emailJsonObject["emailaddress"].stringValue self.emailType = emailJsonObject["emailtype"].stringValue } var email: String var emailType: String } func == (lhs: Email, rhs: Email) -> Bool { return lhs.email == rhs.email && lhs.emailType == rhs.emailType }

Arrays

现在,如果我有两个let newEmails = emailsJsonObjects.map({ return Email(JSON: $0)! }).sort({ $0.0.email < $0.1.email }) let currentEmails = (self.emails as! [Email]).sort({ $0.0.email < $0.1.email })

email

两者都有一个元素,它们具有相同的emailType(lldb) po newEmails.count 1 (lldb) po currentEmails.count 1 (lldb) po newEmails == currentEmails false (lldb) po newEmails[0] == currentEmails[0] true ,这是我通过比较得到的:

setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH,   COOKIE_DOMAIN );

我错过了什么吗?比较是不同的?

1 个答案:

答案 0 :(得分:3)

问题是,因为你的对象继承自NSObject,所以数组正在使用isEqual()进行数组元素的比较。将以下覆盖添加到类定义

override func isEqual(object: AnyObject?) -> Bool
{
    if let rhs = object as? Email
    {
        return self.email == rhs.email && self.emailType == rhs.emailType
    }
    return false
}

一切都会好的。