bea*_*ain 22 arrays variadic-functions swift
在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
}
Run Code Online (Sandbox Code Playgroud)
这个averageOf实现对我来说似乎很合理,但它不能编译.当您尝试调用时,它会出现以下错误sumOf(numbers):
Could not find an overload for '__converstion' that accepts the supplied arguments
Run Code Online (Sandbox Code Playgroud)
里面averageOf,numbers有类型Int[].我相信sumOf期待一个元组而不是阵列.
因此,在Swift中,如何将数组转换为元组?
Jea*_*let 24
这与元组无关.无论如何,在一般情况下,不可能从数组转换为元组,因为数组可以具有任何长度,并且必须在编译时知道元组的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, 5, 1)
func averageOf(_ numbers: Int...) -> Int {
// This calls the first function directly
return sumOf(numbers) / numbers.count
}
averageOf(2, 5, 1)
Run Code Online (Sandbox Code Playgroud)
也许有更好的方法(例如,Scala使用特殊类型的ascription来避免需要重载;你可以sumOf(numbers: _*)从内部编写Scala averageOf而不定义两个函数),但我还没有在文档中找到它.