在 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
}
This averageOf
实现对我来说似乎是合理的,但它无法编译。当您尝试调用时会出现以下错误sumOf(numbers)
:
Could not find an overload for '__converstion' that accepts the supplied arguments
Inside 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 使用特殊的类型归属来避免需要重载;您可以用 Scala 编写sumOf(numbers: _*)
从内部averageOf
没有定义两个函数),但我没有在文档中找到它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)