My favourite feature in Swift 4.1 is conditional conformance, but I noticed that it doesn't seem to be possible to conditionally conform something to the same protocol multiple times:
protocol TestProtocol { }
struct TestStruct<T> { }
extension TestStruct: TestProtocol where T == String { }
extension TestStruct: TestProtocol where T == Int { }
Redundant conformance of 'TestStruct' to protocol 'TestProtocol'
The reason I came across this was because I was trying to make an Array
conform to Equatable
when its element was a specific custom protocol. That protocol defined its own way of comparing any two conforming objects for equality, even if they weren't the same concrete types:
protocol AnyDataType {
func isEqual(to otherDataType: AnyDataType) -> Bool
}
My attempt to conform Array
(which would allow me to compare two [AnyDataType]
, and even two [[AnyDataType]]
):
extension Array: Equatable where Element == AnyDataType {
static func == (lhs: [Element], rhs: [Element]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
return !zip(lhs, rhs).map({ $0.isEqual(to: $1) }).contains(false)
}
}
This compiles, but it generates the following warning, and such arrays don't appear to actually be Equatable
anyway:
Conformance of 'Array' to protocol 'Equatable' was already stated in the type's module 'Swift'
I'm guessing this is just a limitation in Swift, and it can't (yet) do what I'm trying to get it do to. But I wanted to confirm if that was the case, and if there was a reason for this limitation.