2

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?

Pawel Jurczyk
  • 165
  • 2
  • 10
  • I don't think so, for swift it is just the type you specified, unless not cast to anything else, like you did with object1. – d4Rk Dec 24 '18 at 10:19
  • @d4Rk Yes, but I can't go and start casting everything if I have several subclasses, I'd have to have switches on types everywhere – Pawel Jurczyk Dec 24 '18 at 10:23
  • 1
    Maybe this https://stackoverflow.com/q/39007960/2019384 or this https://stackoverflow.com/q/31431753/2019384 helps? – d4Rk Dec 24 '18 at 10:30

0 Answers0