Why is removeAll(where:) function available for arrays but not sets?

The Array struct offers a function removeAll(where:) (docs) that removes all elements matching the provided predicate. I noticed that this function is not provided for the Set struct, and I'm wondering if there is any particular reason for that. Maybe it just comes down to sets getting much less usage than arrays and it simply wasn't provided, or maybe there is a good reason I'm not privy to.

I have a set that I want to remove elements from matching a predicate and am about to write an extension, but I wanted to ask as this piqued my curiosity.

1 Like

Pragmatically, the answer is because Array gets that method from the RangeReplaceableCollection protocol, which Set does not (and cannot) conform to.

Furthermore, the implementation for Array is non-trivial and easy to get wrong (ie. accidentally quadratic) whereas the obvious implementation for Set remains linear.

Nonetheless, the method is indeed useful on Set, and a naive implementation would likely trigger an unintended copy-on-write that duplicates the entire storage of the set.

So I think that a proposal to add removeAll(where:) to Set would be looked upon favorably.

Terms of Service

Privacy Policy

Cookie Policy