2

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?

Robo Robok
  • 21,132
  • 17
  • 68
  • 126

1 Answers1

3

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)})
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Modifying any functions is not an option, I was curious if Swift is flexible enough to handle it this way. I like the solution with a closure, it was also one of my first ideas, but still I decided to ask. I will post a suggestion to Swift community. Being able to use functions with bound values would be pretty cool, but I'm aware that it would be probably too big change to the implementation. Worth trying though :) – Robo Robok Jan 10 '19 at 07:53