Swift Combine: removeDuplicates(), you can totally misuse it if you don’t read this.

Let’s learn about removeDuplicates(). As the name suggests, it removes the duplicates. But it works in a little bit different way that you might expect.

Applying removeDuplicates() — this is not what you expect

let words = ["apple", "apple", "fruit", "apple", "mango", "watermelon", "apple"]
words.publisher
.removeDuplicates()
.sink {
print($0) // apple, fruit, apple, mango, watermelon, apple
}

For this example, I prepared an array. You can see now apple appeared four times in the string. Obviously, apple is duplicate.

But the result is completely the opposite of what you have expected!

Duplicate values still remain…

Only second element of the duplicate element apple is removed...

Why is that?

In reactive programming, everything is coming to you as a sequence of that event.

If two different events are coming and if they are the same exact value Apple in this case, it is going to start removing those duplicates.

Conclusion and Warning!!!

removeDuplicate() works only when the same value appears consecutively.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!