在Swift中,如何将数组转换为元组?
问题出现了,因为我试图调用一个函数,该函数在一个带有可变数量参数的函数中接受可变数量的参数。
- // Function 1
- func sumOf(numbers: Int...) -> Int {
- var sum = 0
- for number in numbers {
- sum += number
- }
- return sum
- }
- // Example Usage
- sumOf(2,5,1)
- // Function 2
- func averageOf(numbers: Int...) -> Int {
- return sumOf(numbers) / numbers.count
- }
这个平均的实现对我来说似乎是合理的,但它不能编译。当您尝试调用sumOf(数字)时,它会出现以下错误:
- Could not find an overload for '__converstion' that accepts the supplied arguments
在averageOf内,数字的类型为Int []。我相信sumOf期待一个元组而不是一个数组。
因此,在Swift中,如何将数组转换为元组?
这与元组无关。无论如何,在一般情况下,不可能从数组转换为元组,因为数组可以具有任何长度,并且必须在编译时知道元组的arity。
但是,您可以通过提供重载来解决您的问题:
- // 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,1)
- func averageOf(_ numbers: Int...) -> Int {
- // This calls the first function directly
- return sumOf(numbers) / numbers.count
- }
- averageOf(2,1)
也许有更好的方法(例如,Scala使用特殊类型的ascription来避免需要重载;你可以在averageOf中写入Scala sumOf(数字:_ *)而不定义两个函数),但我还没有找到它文档。