Overridden == function for Equatable type not called for custom class that subclasses NSCoding and NSObject [duplicate]

↘锁芯ラ 提交于 2019-12-03 22:51:36

Because your class inherits from NSObject you do not need to use the swift protocol Equatable instead you must override the NSObject method isEquals:

Swift 3.x

class FooBar: NSObject, NSCoding {
  override func isEqual(_ object: Any?) -> Bool {
    return id == (object as? FooBar)?.id
  }
}

(Thanks to Kamchatka)

Swift 2.x

class FooBar: NSObject, NSCoding {
  override func isEqual(object: AnyObject?) -> Bool {
    return id == (object as? FooBar)?.id
  }
}

You are getting this error because NSObject already conforms to Equatable through its isEqual method.

So I'm not sure if this is the correct way of doing this, but you could override the isEqual method of NSObject:

class FooBar: NSObject, NSCoding {
...

override func isEqual(object: AnyObject?) -> Bool {
    return self == (object as? FooBar)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!