skip to Main Content
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

2

Answers


  1. 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)
        }
    }
    
    Login or Signup to reply.
  2. 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)
        }
    }
    

    As swift allows method overloading, you may use the same function name with different signatures.
    In your example class methods have different signatures, comparing to the protocol methods, so it is fine. However class methods have default values and can be called without full signature and in this case it is ambiguous as the signature become the same.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search