0

Here is the code

protocol Hello {
    func hello()
}

extension Hello {
    func hello() {
        print("hello")
    }
}

protocol Namable {
    var name: String { get }
}

extension Namable {
    var name: String {
         return "wang"
    }
}

extension Hello where Self: Namable {
    func hello() {
        print("hello, \(name)")
    }
}

class A: Hello {

}
class B: A, Namable {

}

B().hello()

For this code, we have two implementations for the method Hello#hello(), one is in the extension Hello, the other is in the extension Hello where Self: Namable, so for class B: A, Namable, when we call func hello(), which implementation it will take ? in this example, swift will call the implementation in extension Hello where Self: Namable, but I'm not sure if it is take that one purposely, or randomly. Because it doesn't work this way in my other example. Does anyone knows how it works ?

JIE WANG
  • 1,875
  • 1
  • 17
  • 27
  • 1
    This might help you: https://stackoverflow.com/questions/31431753/swift-protocol-extensions-overriding – Cristik Mar 13 '18 at 09:58
  • 1
    The `extension Hello where Self: Namable` implementation will be called when Swift knows the static type of the instance is `B`, as that's the more tightly constrained implementation. However if Swift didn't know the static type of the instance was `B` (i.e it was typed as `Hello` or `A`), then the `extension Hello` implementation will be called, as `A` states its conformance to `Hello`, not `B` – compare https://stackoverflow.com/q/44703205/2976878 – Hamish Mar 13 '18 at 10:39

0 Answers0