Can we bind parameters values when passing functions in Swift?

Viewed 2018

We can pass functions in Swift like this:

func celebrate(callback: (String, String) -> String) -> String {
    return callback("", "") + ""
}

func glam(item1: String, item2: String) -> String {
    return item1 + "" + item2
}

celebrate(callback: glam) // glam function being passed

Recently I learned that it can also be passed this way:

celebrate(callback: glam(item1:item2:)) // great for function overloading

I thought that it would be awesome if this syntax allowed to bind values when passing the function, something like JavaScript allows with .bind(). It could allow to pass functions requiring more parameters that those used by the caller:

func fun(item1: String, item2: String, item3: String) -> String {
    return item1 + "" + item2 + "" + item3
}

celebrate(callback: fun) // obviously won't work, because the arguments number doesn't match

// this is the goal, but with invalid syntax:
celebrate(callback: fun(item1:item2="":item3:))

I know this example is a little twisted, but I hope the point is clear. I'm trying to give a static value to one of the parameters during passing a function.

Can it be done with Swift?

1 Answers

Swift functions are unfortunately not that flexible :(

What you are trying to do is quite similar to currying, which used to be a feature of Swift, but later removed.

You can try to modify the curry function show in this question to curry a function's second argument, but that is not so useful, as it is not a general solution. You would have to write a separate curry for 1 parameter functions, 2 parameter functions, 3 parameter functions etc. For each of those, you also need a separate curry to curry the 1st parameter, the 2nd parameter, the 3rd parameter... There are simply too many cases.

I would just use a closure:

celebrate(callback: {fun(item1: $0, item2: "", item3: $1)})
Related