Search code examples
iosswiftprotocols

swift protocol conformance with duplicate function names


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


Solution

  • 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)
        }
    }