I have a simple protocol with a default method:
public protocol Renderable {
func render() -> String
}
public extension Renderable {
func render() -> String {
"[Renderable]"
}
}
Then there is an advanced class A
, which is a Renderable with its own implementation of render()
class A : Renderable {
public func render(separator: String = "") -> String { ... }
}
Somewhere else a class has a computed property that returns this protocol:
open var test: Renderable { return A(); }
When I call test.render() it outputs "[Renderable]", so the Protocol-method gets called.
I would have expected, that A
's overridden render()
gets called, because I returned an A.
It does as expected, when I change test
to be an A
however I would like to keep it general, so that I can assign different objects to it, and then call their specialized render()
func.
Seems as if the complier downcasts anything in test to plain Renderable
. Can anyone point me in the right direction? What am I understanding wrong here?