Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Disambiguate overloaded functions with identical signatures

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading