8

Suppose that we have several overloaded functions in one class:

func appendToABC(string s: String) -> String {
    return "ABC \(s)"
}

func appendToABC(duplicatedString s: String) -> String {
    return "ABC \(s)\(s)"
}

And we have some API that gets function as an argument:

func printString(function: (String) -> String) {
    print(function("ASD"))
}

How can we pass one of appendToABC functions as an argument to a printString function?

I've thought about wrapping the function with a closure, but it doesn't look nice

printString { appendToABC(duplicatedString: $0) }
Anton Tyutin
  • 626
  • 1
  • 5
  • 15
  • 3
    It is possible if the functions differ in their argument or return types (http://stackoverflow.com/questions/33803888/specify-type-of-polymorphic-function-to-pass-it-as-argument). But I don't think it is possible if the functions differ *only* in the external parameter names. – Martin R Jan 08 '16 at 13:30

1 Answers1

5

This is a known limitation in Swift. There is an open proposal to address it. Currently the only solution is a closure.

Note that this is true of many things in Swift. You also can't refer to properties directly as functions, even though they behave like functions. You must use a closure. And even some free functions cannot be directly passed (print is the most common example).

Rob Napier
  • 286,113
  • 34
  • 456
  • 610