我有一个自定义类(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
}
当我像这样扩展等投票选项时:
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:termining with uncaught exception of type nsexception”错误
如何告诉collectiontype中的“==”使用votingoption的全局函数?
最佳答案
这里有一个解决方案可以实现duplicates
和hasDuplicates
两次,一次用于Equatable
元素,一次用于您的VotingOptions
类。为了尽可能减少代码重复,我定义了一个用于查找重复项的通用实现,它允许您传递一个函数/闭包,该函数/闭包比较两个元素:
extension CollectionType {
func findDuplicates(checkEqual: (Self.Generator.Element, Self.Generator.Element) -> Bool) -> [Self.Generator.Element]{
return self.filter { element in
return self.filter { checkEqual($0, element) }.count != 1
}
}
}
extension CollectionType where Self.Generator.Element : Equatable {
var duplicates: [Self.Generator.Element]{
return self.findDuplicates(==)
}
var hasDuplicates: Bool {
return (self.duplicates.count != 0)
}
}
extension CollectionType where Self.Generator.Element : VotingOption {
var duplicates: [Self.Generator.Element]{
return self.findDuplicates {lhs, rhs in
return (lhs.location?.title.lowercaseString == rhs.location?.title.lowercaseString) && (lhs.startDate == rhs.startDate)
}
}
var hasDuplicates: Bool {
return (self.duplicates.count != 0)
}
}