在 Swift 中将数组传递给具有可变数量参数的函数

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)