Ambiguous use of function with trailing closures

Running into an interesting compiler error using Xcode 12 (swift 5.3) and higher with trailing closures. The following code compiled previously, but now emits an "Ambiguous use of 'to'" error unable to discern between the two functions below.

struct Binder {
    func to<V>(value: V) {}
    
    func to<V>(factory: () -> V) {}
}

Binder().to { 3 } // error: Ambiguous use of 'to'

Curious if this is expected behavior now? Feels a little strange for the compiler to infer a single trailing closure function as "equivalent" to a function accepting a single param value (without any closures), but can also see how it fits in.

I'm surprised this ever worked, but I suppose some limitations/rules around trailing closures were probably lifted when multiple trailing closures were implemented. It now works the same way as

struct Binder {
  func to<V>(x: V) { }
  func to<V>(x: () -> V) { }
}

Binder().to(x: { 3 }) // error: Ambiguous use of 'to(x:)'

which is what I would personally expect. I haven't checked if this particular source break was noted at the time, though.

1 Like

I think the compiler is correct to consider to ambiguous, since V in the first function can be any type, including () -> Int.

This is just another case where it would be great if we can use the first trailing closure parameter's label.

1 Like

I remember seeing an SR with a similar case, but don't remember exactly which was ...
cc @xedin @Douglas_Gregor

Terms of Service

Privacy Policy

Cookie Policy