11

编译时 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 吗?

4

2 回答 2

27

继承的类NSObject已经符合Equatable. 所以声明Object: Equatable是多余的。

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

static func ==(lhs: Object, rhs: Object) -> Bool {
   return lhs.text == rhs.text
}
于 2018-02-21T20:16:05.170 回答
16

根据文档NSObject符合Equatable

符合
CVarArgType
CustomDebugStringConvertible
CustomStringConvertible
Equatable
Hashable
NSObjectProtocol

...因此,就像您的错误所说,符合 Equatable 是多余的...

于 2016-05-23T11:55:44.780 回答