Home > Mobile >  Can you "apply" a function to a "package" of arguments in Swift somehow?
Can you "apply" a function to a "package" of arguments in Swift somehow?

Time:03-08

I was wondering if there's a function (or special syntax) which would behave something like the hypothetical apply below (but for arbitrary f; the one given here is just for the sake of example):

func f(a: String, b: String) -> Bool {
    return a == b
}

let argDict = ["a": "foo", "b": "bar"]

apply(f, argDict) // evaluates f(a: "foo", b: "bar") and returns false

It doesn't have to use a dictionary for the arguments (maybe it even can't use a dictionary?); it could use some other datatype or even just some other special syntax, as long as it somehow enables you to package up arguments and then apply a function to them later, as though you had written the arguments in by hand.

If not for all functions, what about for special classes of functions, like functions with variadic arguments? For example, it would be nice to be able to apply a function with signature (Double...) -> Double to an array of type [Double] as though we had inlined the values.

And if it doesn't already exist as a built-in, can it be constructed?

(Also, I'm not looking to redefine f; if you wanted to, I think you could just redefine it via f1(dict: [String: String]) -> Bool { ... } and then use dict["a"] and dict["b"] in the body instead in place of a and b. But I'm asking this question because I'm curious about the language capabilities here, not because I'm trying to solve a specific problem.)

CodePudding user response:

Swift used to have that. You could pass a tuple of the arguments rather than the arguments directly, which is exactly what you're describing (a strongly-typed argument package). It was called "tuple splat." It was removed in Swift 3. See the SE for the background and why it was removed.

  • Related