How to forward functions with variadic parameters?

前端 未结 4 1376
佛祖请我去吃肉
佛祖请我去吃肉 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:40

    As of Swift 4.1 (in Xcode 9.2), there is no need to overload with sumOf(_ numbers: Int...), the function that forward variadic parameter(s) will IMPLICITLY change it to a single parameter of array of individual parameter(s). E.g. the following code will work without the overloading:

    // This function does the actual work
    func sumOf(_ numbers: [Int]) -> Int {
        return numbers.reduce(0, +) // functional style with reduce
    }
    
    func averageOf(_ numbers: Int...) -> Int {
        // This calls the first function directly
        return sumOf(numbers) / numbers.count
    }
    

    print(averageOf(2, 5, 1))

    Don't know whether this is a bug of the compiler or not :)

提交回复
热议问题