How to forward functions with variadic parameters?

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

    This has nothing to do with tuples. Anyway, it isn't possible to convert from an array to a tuple in the general case, as the arrays can have any length, and the arity of a tuple must be known at compile time.

    However, you can solve your problem by providing overloads:

    // This function does the actual work
    func sumOf(_ numbers: [Int]) -> Int {
        return numbers.reduce(0, +) // functional style with reduce
    }
    
    // This overload allows the variadic notation and
    // forwards its args to the function above
    func sumOf(_ numbers: Int...) -> Int {
        return sumOf(numbers)
    }
    
    sumOf(2, 5, 1)
    
    func averageOf(_ numbers: Int...) -> Int {
        // This calls the first function directly
        return sumOf(numbers) / numbers.count
    }
    
    averageOf(2, 5, 1)
    

    Maybe there is a better way (e.g., Scala uses a special type ascription to avoid needing the overload; you could write in Scala sumOf(numbers: _*) from within averageOf without defining two functions), but I haven't found it in the docs.

提交回复
热议问题