Can I add protocol conformance to a protocol via a swift extension?
//Plain old protocol here
protocol MyData {
var myDataID: Int { get }
}
<
As the error message says: an extension of a protocol cannot have an inheritance clause. Instead, you could make MyData
protocol inherit from Equatable
in the original declaration.
protocol MyData: Equatable {
var myDataID: Int { get }
}
You could then extend add an implementation of ==
for types that conform to MyData
:
func == (lhs: T, rhs: T) -> Bool {
return lhs.myDataID == rhs.myDataID
}
However, I would highly not recommend this! If you add more properties to conforming types, their properties won't be checked for equality. Take the example below:
struct SomeData: MyData {
var myDataID: Int
var myOtherData: String
}
let b1 = SomeData(myDataID: 1, myOtherData: "String1")
let b2 = SomeData(myDataID: 1, myOtherData: "String2")
b1 == b2 // true, although `myOtherData` properties aren't equal.
In the case above you'd need to override ==
for SomeData
for the correct result, thus making the ==
that accepts MyData
redundant.