I know the title of this question is confusing but the weird behaviour is explained in the example below:
protocol Protocol {
func method() -> String
The problem is that c1
and c2
are of type Protocol
, as you've defined their type explicitly this way (remember: protocols are fully fledged types). This means, when calling method()
, Swift calls Protocol.method
.
If you define something like:
let c3 = SuperClass()
...c3
is of type SuperClass
. As SuperClass
has no more specific method()
declaration, Protocol.method()
is still used, when calling c3.method()
.
If you define something like:
let c4 = SubClass()
...c4
is of type SubClass
. As SubClass
does have a more specific method()
declaration, SubClass.method()
is used, when calling c4.method()
.
You could also get c2
to call SubClass.method()
, by down-casting it to `SubClass:
(c2 as! SubClass).method() // returns "From Class2"
Here's a demonstration on SwiftStub.