Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using overloaded functions as first class citizens

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) }
like image 688
Anton Tyutin Avatar asked Jan 08 '16 13:01

Anton Tyutin


1 Answers

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).

like image 164
Rob Napier Avatar answered Nov 13 '22 20:11

Rob Napier