我可以通过快速扩展添加协议一致的协议吗?
//Plain old protocol here protocol MyData { var myDataID: Int { get } }
我想使默认的MyData协议相当(只是比较ID)
extension MyData : Equatable { }
但是我得到这个可爱的错误:
“Extension of protocol ‘MyData’ cannot have an inheritance clause”
我正在寻找的行为是符合Equatable(协议)的BananaData,因为它实现了MyData协议,该协议可以提供Equatable
//This is the method to implement Equatable func ==(lhs: MyData,rhs: MyData) -> Bool { return lhs.myDataID == rhs.myDataID } struct BananaData: MyData { var myDataID: Int = 1 } func checkEquatable(bananaOne: BananaData,bananaTwo: BananaData) { //This compiles,verifying that BananaData can be compared if bananaOne == bananaTwo { } //But BananaData is not convertible to Equatable,which is what I want let equatableBanana = bananaOne as Equatable //I don't get the additional operations added to Equatable (!=) if bananaOne != bananaTwo { } //Error }
由于错误消息说:协议的扩展不能有继承子句.相反,您可以使MyData协议在原始声明中从Equatable继承.
protocol MyData: Equatable { var myDataID: Int { get } }
func == <T: MyData>(lhs: T,rhs: T) -> Bool { return lhs.myDataID == rhs.myDataID }
但是,我不会推荐这个!如果您添加更多属性到符合类型,则不会检查其属性是否相等.举个例子:
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.
在上述情况下,您需要为SomeData重写==以获得正确的结果,从而使得接受MyData冗余的==.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。