本文介绍了将数组传递给 Swift 中具有可变数量参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 编程语言,它说:

函数也可以接受可变数量的参数,将它们收集到一个数组中.

  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 不在语言中然而,正如开发人员所证实的那样.目前的解决方法是使用重载,如果无法添加重载,则等待.

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 中具有可变数量参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 00:56