问题描述
在 Swift 编程语言,它说:
函数也可以接受可变数量的参数,将它们收集到一个数组中.
Functions can also take a variable number of arguments, collecting them into an array.
func sumOf(numbers: Int...) -> Int {
...
}
当我使用逗号分隔的数字列表 (`sumOf(1, 2, 3, 4) 调用此类函数时,它们在函数内作为数组可用.
When I call such a function with a comma-separated list of numbers (`sumOf(1, 2, 3, 4), they are made available as an array inside the function.
问题:如果我已经有一个数字数组想要传递给这个函数怎么办?
Question: what if I already have an array of numbers that I want to pass to this function?
let numbers = [1, 2, 3, 4]
sumOf(numbers)
这会失败并出现编译器错误,找不到接受提供的参数的 '__conversion' 的重载".有没有办法将现有数组转换为可以传递给可变参数函数的元素列表?
This fails with a compiler error, "Could not find an overload for '__conversion' that accepts the supplied arguments". Is there a way to turn an existing array into a list of elements that I can pass to a variadic function?
推荐答案
Splatting is not in the language然而,正如开发人员所证实的那样.目前的解决方法是使用重载,或者如果无法添加重载则等待.
Splatting is not in the language yet, as confirmed by the devs. Workaround for now is to use an overload or wait if you cannot add overloads.
这篇关于在 Swift 中将数组传递给具有可变数量参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!