[swift-evolution] [Idea] Passing an Array to Variadic Functions

Daniel Duan daniel at duan.org
Mon Apr 18 13:14:40 CDT 2016


Justin Jia via swift-evolution <swift-evolution at ...> writes:

> 
> Hi!Currently, we can’t call a variadic function with an array of arguments.

IMO, this would be a useful addition. Here are my thoughts on the thread so
far as an imaginary Q&A.

"Why not remove vararg instead?"

As others have mentioned, this feature enable us to write cleaner code. I
first learned to appreciate it in C, where some books would introduce it as the
way to implement printf(). I really prefer not to create an array on unrelated
items just to print() them in Swift.

"Will it be useful in real life?"

If we keep vararg, then enhancing it with a splat feature will make it far
more useful than it is today. One of my colleague (hi Scott!) encountered its
limits just last week: once the varadic argumntes becomes an array, there's no
way to get them "back" as arguments. This becomes an issue if our function
needs to forward part of its received arguments recursively to itself. Either
of the following would be great:

func foo(a: Int...) {
    if !a.isEmpty() {
        apply(foo, a.dropFirst()) // imaginary apply function.
        foo(a: #splat(a.dropFirst())) // imaginary splat, syntax TBD.
    }
}


Therefore, +1.





More information about the swift-evolution mailing list