You can see in the image below that I was trying to extend the Collection
protocol to include a method called removingDuplicates
, which is supposed to do exactly what it says. The error that the compiler is displaying seems to directly contradict the definition of the Equatable
protocol. Is this a bug or am I misunderstanding something?

- 3,796
- 3
- 16
- 25
-
6Post your code here as text. – Carcigenicate Mar 31 '18 at 01:12
-
possible duplicate: https://stackoverflow.com/questions/25901105/compare-anyobjects-in-swift-without-casting-them-to-a-specific-type – Garr Godfrey Mar 31 '18 at 01:19
2 Answers
The ==
function (all operators are actually functions in Swift) is a requirement of the Equatable
protocol, which means it must be used with some concrete implementations of the protocol.
Another aspect is that Collection
is a generic type, and its Element
associated type will need to eventually be also filled with a concrete type, and == Equatable
doesn't help here.
Actually it's not even possible to have a collection of generic Equatable
values, as Equatable
is a protocol with Self
requirements, thus it can be directly referenced in a lot of places, e.g. [Equatable]
, one reason being the fact that that declaration can't satisfy the "collections are homogenous" requirement as you'd be able ot place two completely unrelated types in the array that way.
What you need to do is to transform the equality where
clause to a conformance one: extension Collection where Element: Equatable
. This moves the burden of providing an actual implementation on the user of the extension. And allows you to use the support brought by the Equatable
type.

- 30,989
- 25
- 91
- 127