Although Alain's solution is very nice, here's somewhat more swifty way which benefits from KeyPaths:
extension Array {
func filterDuplicates(by keyPath: PartialKeyPath<Element>) -> Self {
var uniqueKeys = Set<String>()
return self.filter { uniqueKeys.insert("\($0[keyPath: keyPath])").inserted }
}
}
Now you can use it like this:
yourArr.filterDuplicates(by: \YourClass.propertyName)
And if you want to use multiple properties to determine uniqueness, here's the solution for that:
extension Array {
func withRemovedDuplicates(by keyPaths: PartialKeyPath<Element>...) -> Self {
var uniqueKeys = Set<String>()
return self.filter { element in
uniqueKeys.insert(keyPaths.map { "\(element[keyPath: $0])" }.joined()).inserted
}
}
}
Use is this way:
yourArr.filterDuplicates(by: \YourClass.propertyOneName, \YourClass.propertyTwoName)