Trying to get my head around Protocol oriented programming in Swift and how the extensions work and what level of extensibility it can provide.
Have the following code snippet which I ran through Playgrounds
protocol ProtocolA {
func doSomethingA()
}
protocol ProtocolB {
func doSomethingB()
}
protocol ProtocolC {
func doSomethingC()
}
extension ProtocolA {
func doSomethingA() {
print("Extension - doSomethingA")
}
}
extension ProtocolA where Self: ProtocolB {
func doSomethingA() {
print("Extension - doSomethingA Self: ProtocolB")
}
}
extension ProtocolA where Self: ProtocolC {
func doSomethingA() {
print("Extension - doSomethingA Self: ProtocolC")
}
}
extension ProtocolA where Self: ProtocolB, Self: ProtocolC {
func doSomethingA() {
print("Extension - doSomethingA Self: ProtocolB, ProtocolC")
}
}
extension ProtocolB {
func doSomethingB() {
print("Extension - doSomethingB")
}
}
extension ProtocolC {
func doSomethingC() {
print("Extension - doSomethingC")
}
}
class Implementation: ProtocolA, ProtocolB, ProtocolC {
}
let obj = Implementation()
obj.doSomethingA()
What I get printed is:
Extension - doSomethingA Self: ProtocolB, ProtocolC
Is there anyway that I can guarantee all the extensions to run.
Ideally I'd like to get the following output.
Extension - doSomethingA
Extension - doSomethingA Self: ProtocolB
Extension - doSomethingA Self: ProtocolC
Extension - doSomethingA Self: ProtocolB, ProtocolC
I do understand that Swift, will choose the strongest match in terms of it's types, in fact if I don't provide an implementation where ProtocolA matches both ProtocolB and ProtocolC, I would get a compile time error. Is there anyway that I can go around this?
Thanks.
