[swift-users] Protocol extension code executed instead of class code

Diego Sánchez diego.sanchezr at gmail.com
Sat Feb 20 06:41:19 CST 2016


Consider the following code

protocol MyProtocol {
    func doSomething()
}

extension MyProtocol {
    func doSomething() {
        print("default impl")
    }
}

class A: MyProtocol {}

class B: A {
    func doSomething() {
        print("B impl")
    }
}

let a: MyProtocol = A()
a.doSomething() // Prints "default impl"
let b: MyProtocol = B()
b.doSomething() // Prints "default impl" instead of "B impl"!

Now let's override doSomething in A...

class A: MyProtocol {
    func doSomething() {
        print("A impl")
    }
}

class B: A {
     override func doSomething() {
        print("B impl")
    }
}

let a: MyProtocol = A()
a.doSomething() // Now it prints "A impl"
let b: MyProtocol = B()
b.doSomething() // Now it prints "B impl"

That's clearly inconsistent. I would expect to print "B impl" in the first
case; or maybe always "default impl" (I highly prefer the first option)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160220/be83b16b/attachment.html>


More information about the swift-users mailing list