Passing an array to a function with variable number of args in Swift(在 Swift 中将数组传递给具有可变数量参数的函数)
问题描述
在 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 中将数组传递给具有可变数量参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Swift 中将数组传递给具有可变数量参数的函数


- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01