Reputation: 8810
I have a bunch of structs that define my value types. Many of them conform to a protocol I have called 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).
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
.
Upvotes: 0
Views: 2608
Reputation: 535139
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:
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.
Upvotes: 2