简体   繁体   English

用协议扩展符合协议的结构

[英]Extend structs that conform to a protocol with a protocol

I have a bunch of structs that define my value types. 我有一堆定义我的值类型的结构。 Many of them conform to a protocol I have called DictConvertible . 它们中的许多都符合我称为DictConvertible的协议。 I would like to make an extension that says that everything that implements DictConvertible will get this extension that implements DataRepresentable (from the Haneke cache project ). 我想做一个扩展,说所有实现DictConvertible都会得到这个实现DataRepresentable扩展(来自Haneke缓存项目 )。

Is there a good way that I can express this? 有什么好办法可以表达我的意思吗? I thought I could do 我以为我可以

extension DictConvertible : DataRepresentable { ... }

but I was mistaken 但我误会了

Update: I wasn't very clear, but the reason I wanted to make an extension is so that I can implement the functions defined in DataRepresentable so that I don't have to implement it in every struct that implements DictConvertible . 更新:我不是很清楚,但是我想要进行扩展的原因是,我可以实现DataRepresentable定义的功能,这样我就不必在实现DictConvertible每个结构中都实现DictConvertible

Correct: you cannot extend a protocol to conform to ("inherit" from) another protocol. 正确:您不能扩展协议以遵循(从其他协议“继承”)协议。 You should simply define the protocol to conform to the other protocol: 您应该简单地定义协议以符合其他协议:

protocol DictConvertible : DataRepresentable {
     // ... and the rest as you already have it ...
}

Having done that, you can indeed then extend DictConvertible to provide default implementations of whatever DataRepresentable requires: 完成此操作后,您实际上可以扩展DictConvertible来提供DataRepresentable所需的默认实现:

extension DictConvertible {
    func functionRequiredByDataRepresentable() {
        // ... code ...
    }
}

Alternatively, define a protocol that conforms to both of them: 或者,定义一个符合它们两者的协议:

protocol DictConvertibleAndDataRepresentable : DictConvertible, DataRepresentable {}

...and now you can make all and only those structs that do conform to both conform to this combining protocol. ...现在您可以使所有仅符合它们的结构都符合此组合协议。 Again, you could then extend this protocol to provide default implementations of whatever DictConvertible or DataRepresentable requires. 同样,您可以扩展该协议以提供DictConvertible或DataRepresentable所需的默认实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM