Swift 2将协议一致性添加到协议中 [英] Swift 2 add protocol conformance to protocols

查看:121
本文介绍了Swift 2将协议一致性添加到协议中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过快速扩展将协议一致性添加到协议中吗?

Can I add protocol conformance to a protocol via a swift extension?

//Plain old protocol here
protocol MyData {
    var myDataID: Int { get }
}

我想默认将MyData协议设置为等价的(只需比较ID)

I want to make the MyData protocol equatable by default (just compare the ID)

extension MyData : Equatable { }

但是我得到了这个可爱的错误:

But I get this lovely error:

协议'MyData'的扩展不能具有继承子句"

"Extension of protocol 'MyData' cannot have an inheritance clause"

我正在寻找的行为是BananaData符合Equatable(一种协议),因为它实现了MyData协议,该协议可以提供Equatable的默认实现

The behavior i'm looking is BananaData conforming to Equatable (a protocol) because it implements the MyData protocol which can provide a default implementation of 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继承.

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 }
}

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

You could then extend add an implementation of == for types that conform to MyData:

func == <T: MyData>(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.

在上述情况下,您需要为SomeData覆盖==以获得正确的结果,从而使接受MyData==成为多余.

In the case above you'd need to override == for SomeData for the correct result, thus making the == that accepts MyData redundant.

这篇关于Swift 2将协议一致性添加到协议中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆