Method overloads with default parameters - why is this not ambiguous?

Why does the following code compile? I'd expect it to complain about ambiguous use of 'x', but that only happens when both methods have the same number of parameters, all with default values :thinking:

struct Foo {

  func x(a: Int = 0, b: Int = 0) {
    
  }

  func x(b: Int = 0) {

  }
}

Foo().x()
1 Like

What I assume is that the compiler considers func x(b: Int = 0) to be the “more specific” method matching the call, and therefore chooses it. I am sure that someone can give a more authoritative answer ...

2 Likes

I suspect you’re right. This behavior is not documented anywhere is it? I too would love an authoritative answer...

It is explained in the compiler code (CSRanking.cpp) as

// If the first function has fewer effective parameters than the
// second, it is more specialized.

tho I'm not a person to tell you if it was a deliberate choice to allow this behavior or something that should be fixed/clarified further.

5 Likes