How to forward functions with variadic parameters?

前端 未结 4 1379
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 21:08

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

4条回答
  •  臣服心动
    2020-12-03 21:30

    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
    }
    

提交回复
热议问题