Last active
June 1, 2020 15:44
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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