数组 – 如何使用可变参数转发函数?

前端之家收集整理的这篇文章主要介绍了数组 – 如何使用可变参数转发函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Swift中,如何将数组转换为元组?

问题出现了,因为我试图调用一个函数,该函数在一个带有可变数量参数的函数中接受可变数量的参数。

  1. // Function 1
  2. func sumOf(numbers: Int...) -> Int {
  3. var sum = 0
  4. for number in numbers {
  5. sum += number
  6. }
  7. return sum
  8. }
  9. // Example Usage
  10. sumOf(2,5,1)
  11.  
  12. // Function 2
  13. func averageOf(numbers: Int...) -> Int {
  14. return sumOf(numbers) / numbers.count
  15. }

这个平均的实现对我来说似乎是合理的,但它不能编译。当您尝试调用sumOf(数字)时,它会出现以下错误

  1. Could not find an overload for '__converstion' that accepts the supplied arguments

在averageOf内,数字的类型为Int []。我相信sumOf期待一个元组而不是一个数组。

因此,在Swift中,如何将数组转换为元组?

这与元组无关。无论如何,在一般情况下,不可能从数组转换为元组,因为数组可以具有任何长度,并且必须在编译时知道元组的arity。

但是,您可以通过提供重载来解决您的问题:

  1. // This function does the actual work
  2. func sumOf(_ numbers: [Int]) -> Int {
  3. return numbers.reduce(0,+) // functional style with reduce
  4. }
  5.  
  6. // This overload allows the variadic notation and
  7. // forwards its args to the function above
  8. func sumOf(_ numbers: Int...) -> Int {
  9. return sumOf(numbers)
  10. }
  11.  
  12. sumOf(2,1)
  13.  
  14. func averageOf(_ numbers: Int...) -> Int {
  15. // This calls the first function directly
  16. return sumOf(numbers) / numbers.count
  17. }
  18.  
  19. averageOf(2,1)

也许有更好的方法(例如,Scala使用特殊类型的ascription来避免需要重载;你可以在averageOf中写入Scala sumOf(数字:_ *)而不定义两个函数),但我还没有找到它文档。

猜你在找的Swift相关文章