In Swift, how do you convert an Array to a Tuple?
The issue came up because I am trying to call a function that takes a variable number of arguments inside a funct
I realize this is an older post, but this came up rather high in the search results and I found a working solution.
You can write the sumOf function to accept an array of integers as the number parameter and overload the sumOf function to accept a variadic input for the numbers parameter which will be passed to the first version as an array. This way the averageOf function can pass its variadic input as array to sumOf.
This does not seem very ideal because you need to overload each function that works like this, but it will work in the way you wanted.
func sumOf(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Function 1
func sumOf(numbers: Int...) -> Int {
return sumOf(numbers: numbers)
}
// Example Usage
sumOf(2, 5, 1)
// Function 2
func averageOf(numbers: Int...) -> Int {
return sumOf(numbers: numbers) / numbers.count
}