我有一个自定义类(VotingOption),它继承自NSManagedObject
,有时我想检查数组中的某些投票选项是否重复。我试图使我的代码尽可能通用。这是我为扩展 CollectionType 协议所做的:
extension CollectionType where Self.Generator.Element : Equatable {
var duplicates: [Self.Generator.Element]{
return = self.filter { element in
return self.filter { $0 == element }.count != 1
}
}
var hasDuplicates: Bool {
return (self.duplicates.count != 0)
}
}
这就像一个魅力,除了它没有使用全局函数:
func ==(lhs: VotingOption, rhs: VotingOption) -> Bool {
return (lhs.location?.title.lowercaseString == rhs.location?.title.lowercaseString) && (lhs.startDate == rhs.startDate)
}
当我做这样的事情时:
let temp: [VotingOption] = votingOptions?.array as? [VotingOption]
if temp.hasDuplicates {
//do something
}
当我像这样在 VotingOption 中扩展 isEqual 时:
class VotingOption: NSManagedObject {
override func isEqual(object: AnyObject?) -> Bool {
if let rhs = object as? VotingOption {
return (self.location?.title.lowercaseString == rhs.location?.title.lowercaseString) && (self.startDate == rhs.startDate)
} else {
return false
}
}
...
...
... rest of class
}
应用程序崩溃并指向 AppDelegate 并显示“libc++abi.dylib:以 NSException 类型的未捕获异常终止”错误
如何告诉 CollectionType 中的“==”使用 VotingOption 的全局函数?