Default value with the same method signature in protocol

Have a question how to handle a case then protocol and class/struct have the same name but one of them has a parameter that defined as a default value.

protocol A {
    func something()
}
class Test {
    func something(value: Bool = true) {
        print("method")
    }
}
extension Test: A {
    func something() {
        print("protocol")
    }
}

let test = Test()
test.something()   // protocol
(test as A).something()   // protocol

In both cases will be called a method with “protocol”. How should I modify this code that was called a method with “method”?

When compiler resolves overloads to decide which function to call, it looks for the closest match. An exact match always wins and it will never call the method with default argument. The only way to make sure your method is called is not to drop the default argument.

There have been discussions about new features that can help resolve this issue. Maybe you can revive this thread on evolution. Basically, if you could use a different name when implementing a protocol, the issue would not come up:

protocol A {
    func something()
}
class Test {
    func something(value: Bool = true) {
        print("method")
    }
}
extension Test: A {
    func somethingOfA() as A.something  { // Not valid syntax now
        print("protocol")
    }
}

let test = Test()
let a: A = Test()
test.something()   // method
test.somethingOfA() // protocol
(test as A).something()   // protocol
a.something() // protocol
3 Likes

@hooman Thank you.