Ole Begemann Ole Begemann - 9 months ago 46
Swift Question

Passing an array to a function with variable number of args in Swift

In The Swift Programming Language, it says:


Functions can also take a variable number of arguments, collecting them into an array.

func sumOf(numbers: Int...) -> Int {
...
}



When I call such a function with a comma-separated list of numbers (`sumOf(1, 2, 3, 4), they are made available as an array inside the function.

Question: what if I already have an array of numbers that I want to pass to this function?

let numbers = [1, 2, 3, 4]
sumOf(numbers)


This fails with a compiler error, “Could not find an overload for '__conversion' that accepts the supplied arguments”. Is there a way to turn an existing array into a list of elements that I can pass to a variadic function?

Answer Source

Splatting is not in the language yet, as confirmed by the devs. Workaround for now is to use an overload or wait if you cannot add overloads.