[swift-evolution] [swift-users] [swift-user]Unexpected behavior of protocol extension.

Vladimir.S svabox at gmail.com
Wed Sep 21 05:54:42 CDT 2016


On 21.09.2016 9:30, Goffredo Marocchi via swift-evolution wrote:
> If the reference to the instance of the class is cast to the protocol type,
> I want other object to be aware of my API contract not the specific class
> instance, then the protocol default method gets called and that is several
> shades of not appropriate for me.

Could you provide some example? I was not able to reproduce such 
behavior(and was not expected to be able):
(Probably, you want to mention helper methods in protocol extension that 
was not defined *in protocol itself*, then yes. But AFAIK not for the 
*default implementation* of protocol requirement i.e. the method/prop that 
*is* declared in "main" protocol definition)

protocol A {
     func foo()
}

extension A {
     func foo() { print("A") }
}

class C : A {
     func foo() { print("C") }
}


let a : A = C()
a.foo() // "C"


func f(a: A) {
     a.foo()
}
f(a: a) // "C"


func g<T>(a: T) where T : A {
     a.foo()
}
g(a: C()) // "C"


func h<T: Sequence>(a: T) where T.Iterator.Element : A {
     for e in a {
         e.foo()
     }
}
h(a: [C()]) // "C"


func i<T: Sequence>(a: T) where T.Iterator.Element == A {
     for e in a {
         e.foo()
     }
}
i(a: [a]) // "C"



More information about the swift-evolution mailing list