Skip to content

Instantly share code, notes, and snippets.

@siempay
Last active June 1, 2020 15:44
Show Gist options
  • Save siempay/64aebc8fc2b838de66da079004bb135b to your computer and use it in GitHub Desktop.
Save siempay/64aebc8fc2b838de66da079004bb135b to your computer and use it in GitHub Desktop.
Array extension for swift language usable in iOS to filter/remove duplicated elements based on a predicate
/// Remove duplicated elements
extension Array {
/// mutate array by iterating through element and filtering duplicated ones
/// - parameter predicate: the test to check if two elements are a dulication
public mutating func removeDuplicates(_ predicate: (Element, Element) -> Bool) {
self = removeDuplicates(predicate)
}
/// iterating through element and filtering duplicated ones
/// - parameter predicate: the test to check if two elements are a dulication
public func removeDuplicates(_ predicate: (Element, Element) -> Bool) -> [Element] {
var result = [Element]()
for value in self {
if !result.contains(where: { elem -> Bool in
predicate(value, elem)
}) {
result.append(value)
}
}
return result
}
}
extension Array where Element: Equatable {
/// Remove duplicated elements where array is equatable
public mutating func removeDuplicates() {
var result = [Element]()
for value in self {
if !result.contains(value) {
result.append(value)
}
}
self = result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment