Protocol Extension Collision Question

Hi,


If I have a struct that conforms to two protocols with the same method - that's fine. If both protocols implement the method in their extension then there is, of course, a problem. In other words, I expect the following to have issues because Thing can't decide which implementation of doThis() it supports. This is the classic diamond problem with multiple inheritance.

=====

protocol OneDoThisable {

func doThis()

}

protocol TwoDoThisable {

func doThis()

}

extension OneDoThisable {

func doThis() {

print("One's implementation")

}

}

extension TwoDoThisable {

func doThis() {

print("Two's implementation")

}

}

struct Thing: OneDoThisable, TwoDoThisable {

}

let thing = Thing()

thing.doThis()

=====



What I'm asking is how could I disambiguate. I'd like to do something like this.


====

struct Thing: OneDoThisable, TwoDoThisable {

func doThis() {

(self as OneDoThisable).doThis()

}

}

====


In my own code I can just change the name of one of the methods. In case of two library protocols colliding... I can't always avoid such a collision and I may just want to choose or combine implementations from the protocol extensions.


Of course, I may be misunderstanding -


Thank you,


Daniel

Replies

What I'm asking is how could I disambiguate. I'd like to do something like this.


====

struct Thing: OneDoThisable, TwoDoThisable {

func doThis() {

(self as OneDoThisable).doThis()

}

}

====

That’s exactly what you should do. We don’t have a good answer if two library protocols choose the same signature and give it different meanings, though, other than creating a separate wrapper type that provides library2’s protocol conformance and not trying to make Thing conform to both protocols.

Thank you