Can I add protocol conformance to a protocol via a swift extension?
//Plain old protocol here
protocol MyData {
var myDataID: Int { get }
}
<
Does this playground do what you want? I made it based on what I understand from Protocol-Oriented Programming in Swift from WWDC 2015.
import Foundation
//Plain old protocol here
func == (lhs: MyData, rhs: MyData) -> Bool {
return lhs.myDataID == rhs.myDataID
}
func != (lhs: MyData, rhs: MyData) -> Bool {
return lhs.myDataID != rhs.myDataID
}
protocol MyData {
var myDataID: Int { get }
}
extension MyData where Self: Equatable {
}
struct BananaData: MyData {
var myDataID: Int = 1
}
func checkEquatable(bananaOne: BananaData, bananaTwo: BananaData) {
//This compiles, verifying that BananaData can be compared
if bananaOne == bananaTwo {
print("Same")
}
//But BananaData is not convertible to Equatable, which is what I want
//I don't get the additional operations added to Equatable (!=)
print(bananaOne.myDataID)
print(bananaTwo.myDataID)
if bananaOne != bananaTwo {
}
//Error
}
let b1 = BananaData(myDataID: 2)
let b2 = BananaData(myDataID: 2)
checkEquatable(b1, bananaTwo: b2)
let c = b1 == b2 // Evaluates as true