[swift-evolution] Proposal SE-0009 Reconsideration

Jeremy Pereira jeremy.j.pereira at googlemail.com
Thu May 19 11:24:12 CDT 2016


> On 19 May 2016, at 13:30, Krystof Vasa via swift-evolution <swift-evolution at swift.org> wrote:
> 
> See this example that demonstrates how it's pretty much unusable (IMHO), since whenever you refer to the instance as to the protocol, the default implementation gets invoked:
> 
> protocol MyProtocol { }
> 
> extension MyProtocol {
> 	func getInt() -> Int {
> 		return 0
> 	}
> }
> 
> class MyClass: MyProtocol {
> 	func getInt() -> Int {
> 		return 1
> 	}
> }
> 
> 
> let instance = MyClass()
> instance.getInt() // 1
> 
> var anyInstance: MyProtocol = instance
> anyInstance.getInt() // 0 !!!!!!!
> 
> 
> Since anyInstance is of MyProtocol type, you get the default implementation (no dynamic dispatch).


That’s because the only information that the compiler has about anyInstance is that it conforms to MyProtocol which has no methods so it doesn’t know that it can dispatch getInt() to the implementation in MyClass. Change the protocol to 

protocol MyProtocol {
    func getInt() -> Int
}

and it will work as expected. 



More information about the swift-evolution mailing list