Using overloaded functions as first class citizens
Asked Answered
S

1

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) }
Sven answered 8/1, 2016 at 13:17 Comment(1)
It is possible if the functions differ in their argument or return types (#33804388). But I don't think it is possible if the functions differ only in the external parameter names.Robertoroberts
I
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).

Intercontinental answered 8/1, 2016 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.