4

包含方法无法正常工作,即使它与 Object 匹配,它也会给我错误的结果?

我的代码如下

class Generic: NSObject, NSCoding
{

  var genericCode: String?
  var genericName : String?
  var genericType : String?
  var genericImageUrl : String?
  var genericPhone: String?
  var orgName : String?

  override init()
  {

    self.genericCode = String("")
    self.genericName = String("")
    self.genericType = String("")
    self.genericImageUrl = String("")
    self.genericPhone = String("")
    self.orgName = String("")

  }

  //Parameterzed Constructor for the Generic
  init(genericCode: String , genericName: String , genericPhone: String, genericType: String, genericImageUrl : String)
  {
    self.genericCode = genericCode
    self.genericName = genericName
    self.genericType = genericType
    self.genericImageUrl = genericImageUrl
    self.genericPhone = genericPhone

  }

  required init(coder aDecoder: NSCoder) {
    genericCode = aDecoder.decodeObjectForKey("genericCode") as? String
    genericName = aDecoder.decodeObjectForKey("genericName") as? String
    genericType = aDecoder.decodeObjectForKey("genericType") as? String
    genericPhone = aDecoder.decodeObjectForKey("genericPhone") as? String
  }

  func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(genericCode, forKey: "genericCode")
    aCoder.encodeObject(genericName, forKey: "genericName")
    aCoder.encodeObject(genericType, forKey: "genericType")
    aCoder.encodeObject(genericPhone, forKey: "genericPhone")
  }
}

func ==(lhs: Generic, rhs: Generic) -> Bool
{
  return lhs.genericCode == rhs.genericCode
}

检入 ViewController

print(readArray.contains(generic))
if !readArray.contains(generic)
{
            readArray.append(generic)
}
4

1 回答 1

13

选项1

原因是您的类继承自NSObject,因此,您必须满足以下NSObjectProtocol条件Equatable

override func isEqual(object: AnyObject?) -> Bool {
     if let object = object as? Generic {
         return self.genericCode == object.genericCode
     }
     return false
 }

选项 2

继承自Equatable而不是NSObject(您可能无法使用此选项,因为您似乎需要NSCoding

请注意,对于较新版本的 Swift,您可能应该使用 选项 3:使用Codable而不是NSCodable

于 2016-05-23T13:07:43.113 回答