I have an array of non-Equatable
objects. I want to remove all the duplicates from the array.
class SearchResult { // non-equatable
var index: Int!
var score: Int!
init(_ index: Int, score: Int = 0) {
self.index = index
self.score = score
}
}
var searchResults: [SearchResult] = [SearchResult(0), SearchResult(1), SearchResult(1), SearchResult(2), SearchResult(2)]
searchResults.map { $0.index }
gives us: 0, 1, 1, 2, 2
Currently, I do so by mapping the objects' property index
, which is equatable, since it's an Int
. This way, I can remove the duplicates from the indices array:
let withDupes: [SearchResult] = searchResults
let indices = withDupes.map { $0.index }.removingDuplicates()
For reference, .removingDuplicates()
comes from a post on StackOverflow
Note: this is the part I want to be reviewed.
Then, I get the object with the corresponding index by looping through the indices array and add it to the noDupes
array.
var noDupes: [SearchResult] = []
indices.forEach { (index) in
guard let notADupe = (withDupes.filter { $0.index == index }).first else { return }
noDupes.append(notADupe)
}
noDupes.map { $0.index }
now is: 0, 1, 2
Now, this code works, but it will be executed very often. Since I feel like this is not a very efficient way to remove the duplicates, I fear a performance drop.
How can I improve and / or simplify my code and still successfully remove the duplicates from the array?