对于子类NSCoding和NSObject的自定义类,未调用Equatable类型的==函数 [英] Overridden == function for Equatable type not called for custom class that subclasses NSCoding and NSObject
问题描述
下面的FooBar
类必须覆盖Equatable
类型的==
函数.
The FooBar
class below has to override the ==
function of the Equatable
type.
但是,在FooBar
对象的数组上调用contains
不会导致调用自定义==
函数内部的断点.可能有另一个==
函数覆盖此自定义函数吗?
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?
注意:因为FooBar必须是NSCoding和NSObject的子类,所以FooBar不会将Equatable列为协议,因为它会导致此错误:
Note: Because FooBar must subclass from NSCoding and NSObject, FooBar does not list Equatable as a protocol because it causes this error:
'FooBar'与协议'Equatable'的冗余一致性
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) }
推荐答案
由于您的类继承自NSObject
,因此您无需使用swift协议Equatable
,而必须覆盖NSObject
方法isEquals
:
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
}
}
(感谢堪察加半岛)
Swift 2.x
class FooBar: NSObject, NSCoding {
override func isEqual(object: AnyObject?) -> Bool {
return id == (object as? FooBar)?.id
}
}
这篇关于对于子类NSCoding和NSObject的自定义类,未调用Equatable类型的==函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!