If a function is overloaded in a way that affects its type signature, the Swift compiler can usually disambiguate it from the input and output types. But is there a way to disambiguate the functions if their only difference is in the parameter naming?
Suppose we have the following three function overloads that we attempt to call via some function that takes a function:
func foo(_ name: String) -> String {
return name
}
func foo(name: String) -> String {
return "\(name) \(name)"
}
func foo(name: String) -> Int {
return name.count
}
func printWithFunc(name: String, f: (String) -> String) {
print(f(name))
}
func printWithFunc(name: String, f: (String) -> Int) {
print(f(name))
}
// Does not work since `foo` can refer to any one of
// the three overloaded functions.
printWithFunc(name: "John", f: foo)
// Works fine because there is only one `foo(String) -> Int`.
printWithFunc(name: "John", f: foo as (String) -> Int)
// Does not work since `foo` can refer to either of the two
// first `foo` functions.
printWithFunc(name: "John", f: foo as (String) -> String)
The problems with ambiguous functions is not at all unexpected. But is there a good way to disambiguate it, beyond wrapping the supplied function parameter in a closure like this:
// Works fine because only one of the three `foo` functions has a
// *named* parameter.
printWithFunc(name: "John") { name in
return foo(name: name)
}
>Solution :
You can include the parameter name(s) of the function when passing it to help the compiler identify which one you want to use
printWithFunc(name: "John", f: foo(name:) as (String) -> String)