' Generic'的冗余一致性协议' Equatable'在Swift 2.2中

时间:2016-05-23 11:47:47

标签: swift protocols equatable

编译时我在Equatable中出错。 我想在列表中添加find或contains方法来检查值。 我的代码

class Generic: NSObject, Equatable, NSCoding //Am Having an error -  Redundant conformance of 'Generic' to protocol 'Equatable'

{

  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
}

发生了错误,是因为我正在使用NSCoding和NSobject吗?

2 个答案:

答案 0 :(得分:14)

根据docsNSObject符合Equatable

  

符合
  CVarArgType
  CustomDebugStringConvertible
  CustomStringConvertible
  Equatable
  哈希的
  NSObjectProtocol

...因此,就像你的错误所说的那样,对Equatable的一致性是多余的......

答案 1 :(得分:14)

继承NSObject的类已符合Equatable。因此声明Object: Equatable是多余的。

但是,一致性并不意味着它已经正确实现(NSObject只是检查指针是否相同)。如果您希望为Equatable正确实施NSObject,只需排除协议一致性声明(: Equatable),但仍然实施比较方法:

static func ==(lhs: Object, rhs: Object) -> Bool {
   return lhs.text == rhs.text
}