Consider the below:
protocol AProtocol {
func foo()
}
extension AProtocol {
func foo() {
print("extension")
}
}
class SuperClass: AProtocol { }
class SubClass: SuperClass {
func foo() {
print("SubClass")
}
}
let object1: SuperClass = SubClass()
let object2: AProtocol = SubClass()
let object3: SubClass = SubClass()
object1.foo() // prints "extension"
(object1 as? SubClass)?.foo() // prints "SubClass"
object2.foo() // prints "extension"
object3.foo() // prints "SubClass"
So I never can have a collection of objects that are subclasses of a type that conforms to a protocol with a default implementation? I wish that at least the object2
would correctly use the implementation of the subclass.
So the question really is, can I do it any other way? Is it a bad programming practice?