I just wanted to check whether there contains any duplicates in my array. I searched on Google and see some approaches:
- Double for-loop loops though the array and comparing each item
- Creating a dictionary that stores the number of occurrences of each item
But these methods require a lot of loops and I'm kind of lazy to write a large amount of code just for this functionality. xD.
So I thought of this creative way:
let containsDuplicates = Set(array).count != array.count
However, is this method faster or slower than the other two? I'm not sure because it seems to create a set which I think needs to loop through the array. And I don't know whether accessing the count
also loops through the whole array.
If I only have at most 50 items in the array, will this even matter?