Home > Back-end >  swift protocol conformance with duplicate function names
swift protocol conformance with duplicate function names

Time:10-19

class A {
    func test(string: String, another defaultValue: String = "") {
        ///...
    }
}

class B {
    func test(string: String, different defaultValue: Bool = true) {
        ///...
    }
}

protocol Test {
    func test(string: String)
}

extension A: Test {
    func test(string: String) {
        self.test(string: string)
    }
}

extension B: Test {
    func test(string: String) {
        self.test(string: string)
    }
}

When I do this I get the following error

Function call causes an infinite recursion

How to confirm to the protocol Test to the classes which have similar function names

CodePudding user response:

When A or B conform to Test, there is no way for the program to know which .test you're calling, cause the internal .test methods in A & B have default values.

To resolve the ambiguity, you can be specific:

extension A: Test {
    func test(string: String) {
      self.test(string: string, another: "")
    }
}

extension B: Test {
    func test(string: String) {
      self.test(string: string, different: true)
    }
}

CodePudding user response:

You have to call class methods with full signature:

extension A: Test {
    func test(string: String) {
        self.test(string: string, another: "")
    }
}

extension B: Test {
    func test(string: String) {
        self.test(string: string, different: true)
    }
}
  • Related