Generic Equality

The Array struct type doesn't conform to Equatable. It can't, because its Element type doesn't have to conform to Equatable, so Array cannot enforce it. Nevertheless, if the Element type does conform to Equatable, you can compare Arrays with the same type of element for equality.

You can also nest arrays and compare them, so long as the root type is Equatable. So, you can arrays of arrays of Equatable types. Or arrays of arrays of arrays.

I should add at this point that this ability to compare isn't currently in the documentation for Array structures or any of the protocols it inherits from, but I'm assuming it exists in Swift 2 because of protocol extensions - Array<T> where T : Equatable, or something along those lines.


I've created a generic struct type, let's call it Foo<T>, and like Array I can't make it conform to Equatable because T might not be Equatable. I've written an ==<T> operator which allows for an equality comparison if T is Equatable.

The situation is this: I'd now like to test two arrays of Foo<T> for equality. But because Foo<T> doesn't conform to Equatable, [Foo<T>] doesn't either. Is there a way to make Equatable an 'inheritable' trait from a type's generic component?

Actually this is not working because "extension Array<T> where T : Equatable" is not supported. Protocol extension currently only works for protocols.

But Array is a struct so an can not be extented genericly. There is alreasy another thread on this.

You're right - Array isn't a protocol - what I meant to write was 'extension CollectionType where Self.Generator.Element : Equatable'. Nevertheless, neither CollectionType as a protocol nor Array as a struct provides a documented equality operator if they have equatable elements.


I've just found two other threads on this, and neither of them suggested a way to make a collection of equatables equatable. So for the moment I've written a method which zips the comparable sequences and iterates through them testing for equality; I'd just hoped there was a better way.

Without checking, I think what you're looking for in the standard library is

func ==<Element : Equatable>(lhs: [Element], rhs: [Element]) -> Bool

and these Arrays aren't Equatable, they just implement the == operator.

Generic Equality
 
 
Q