Protocol distribution method in Swift 2.0

I had a problem sending protocol methods.

I have a class hierarchy that looks like this:

protocol E { func test() } extension E { func test() { print("jello") } } class A: E { } class B: A { func test() { print("hello") } } 

But when I call test on an instance of class B , statically forced to type A , "jello" is printed, not "hello".

 let b: A = B() // prints "jello" not "hello" b.test() 

My understanding is that the test "jello" print method "integrates" into instances of A (since A conforms to protocol E ). Then I provide another implementation of test inside B (which inherits form A ). I thought that polymorphism would work here, and calling test on a B instance that is stored inside A would print hello . What's going on here?

It works great when not using any protocol:

 class A { func test() { print("jello") } } class B: A { override func test() { print("hello") } } let b: A = B() // prints "hello" b.test() 

How is it different from adopting a protocol that adds new methods to my parent class and provides a new implementation in a subclass, than wrote this method directly in the parent class and then overrides it in the subclass?

Do you guys have a workaround?

+6
polymorphism ios xcode swift xcode7
source share
2 answers

It smells like a mistake.

The only workaround I came up with was very ugly ...

 protocol E { func test() } func E_test(_s: E) { print("jello") } extension E { func test() { E_test(self) } } class A: E { func test() { E_test(self) } } class B: A { override func test() { print("hello") } } let b: A = B() b.test() 
+3
source share

This is really a mistake. Here is a link to it: https://bugs.swift.org/browse/SR-103

+1
source share

All Articles