在 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
}
这个averageOf
实现对我来说似乎是合理的,但它不能编译。当您尝试调用 sumOf(numbers)
时出现以下错误:
Could not find an overload for '__converstion' that accepts the supplied arguments
在 averageOf
中,numbers
的类型为 Int[]
。我相信 sumOf
需要一个元组而不是数组。
因此,在 Swift 中,如何将数组转换为元组?
最佳答案
这与元组无关。无论如何,在一般情况下不可能从数组转换为元组,因为数组可以有任意长度,并且必须在编译时知道元组的元数。
但是,您可以通过提供重载来解决您的问题:
// 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)
也许有更好的方法(例如,Scala 使用特殊的类型归属来避免需要重载;您可以在 averageOf< 中用 Scala
没有定义两个函数),但我没有在文档中找到它。sumOf(numbers: _*)
编写
关于arrays - 如何转发带有可变参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49380042/