same method in multiple extensions.

Hi, I’m interesting in the behavior of the swift extension,
I was wondering what will swift do when we have multiple implementations of one method in different extensions.

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()

Can we make sure the B().hello() will call the method in
extension Hello where Self: Namable {

func hello() {

    print("hello, \(name)")

}

}

?

Best Regards.

Hello,

You can help forum members read your question (and maybe answer) by editing your message so that your code snippets are properly formatted: wrap code blocks inside triple backticks:

```
let x = 1
```

renders as:

let x = 1

Yes, you can. Since B is namable, it will use the extension with where Self: Namable.
This is because the implementations defined for hello. You could create an other protocol:

protocol Hello2 {
    func hello()
}

extension Hello2 {
   func hello() {
       print("An other hello default implementation")
   }
}

class ClassC: Hello, Hello2 {
    // You have to implement hello() here, because there are two possible implementations
}

To answer your question: The compiler will ensure that there is only one possible implementation.


Shouldn’t this be moved to “Using swift”?