Swift 2添加协议符合协议

前端之家收集整理的这篇文章主要介绍了Swift 2添加协议符合协议前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以通过快速扩展添加协议一致的协议吗?
//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 }
}

然后,可以扩展为符合MyData的类型添加一个==的实现:

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冗余的==.

原文链接:https://www.f2er.com/swift/319810.html

猜你在找的Swift相关文章