Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

The FooBar class below has to override the == function of the Equatable type.

However, calling contains on an array of FooBar objects does not cause a breakpoint inside the custom == function to get invoked. Is it possible another == function is overriding this custom one?

Note: Because FooBar must subclass from NSCoding and NSObject, FooBar does not list Equatable as a protocol because it causes this error:

Redundant conformance of 'FooBar' to protocol 'Equatable'

func ==(lhs: FooBar, rhs: FooBar) -> Bool {     return lhs.id == rhs.id }  class FooBar: NSObject, NSCoding {      // Class def }  // Both serverFooBars and gFooBars are [FooBar] let newFooBars = serverFooBars.filter { !gFooBars.contains($0) } 
like image 952
Crashalot Avatar asked May 07 '16 07:05

Crashalot


2 Answers

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 and above

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   } } 
like image 145
Blake Lockley Avatar answered Sep 28 '22 09:09

Blake Lockley


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) } 
like image 26
Odrakir Avatar answered Sep 28 '22 08:09

Odrakir