ios - 可变参数 v 数组参数

标签 ios swift parameters

<分区>

我正在努力查看在将值传递给函数时使用哪种方法是否有明显的优势。我下面的代码可能不是解释我试图做出的决定的最佳示例,但在我看来,它是最容易理解的。

可变参数方法

func arithmeticMean(numbers: Double...) -> Double {
   var total: Double = 0
   for value in numbers {
      total += value
   }

   return total / Double(numbers.count)
}

arithmeticMean(5, 10, 15)

数组参数法

func arithmeticMean(numbers: [Double]) -> Double {
   var total: Double = 0
   for value in numbers {
       total += value
   }

   return total / Double(numbers.count)
}

arithmeticMean([5, 10, 15])

这两种技术中的哪一种是首选?如果是这样,为什么(速度、可靠性或只是易于阅读)?谢谢。

最佳答案

我认为没有速度差异。因为在函数内部,您使用 Variadic Parameter 就像使用 Array 一样。

  1. 我认为如果参数个数比较少,例如小于 5,Variadic Parameter 可能是更好的解决方案,因为它易于阅读。

  2. 如果参数数量很大。数组是更好的解决方案。

还知道,Variadic Parameter 有一些限制:

A function may have at most one variadic parameter, and it must always appear last in the parameter list, to avoid ambiguity when calling the function with multiple parameters.

If your function has one or more parameters with a default value, and also has a variadic parameter, place the variadic parameter after all the defaulted parameters at the very end of the list.

我的想法,希望对你有帮助

关于ios - 可变参数 v 数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30572738/

相关文章:

ios - 如何在 Swift 中将 PNG 转换为 WebP?

ios - 在 Swift 4 中的两个 TableViewController 之间传递数据不起作用

ios - 'NSSet ?' does not contain a member called ' 生成器'

javascript - 为什么要将参数传递给 CSS 和 JavaScript 链接文件,如 src ="../cnt.js?ver=4.0"?

ios - inviteHandler 从未调用过

iOS - 是否可以在不导入每次定义它的文件的情况下使宏全局可用?

ios - 核心数据在swift ios中再次运行应用程序后显示故障记录?

swift - Array 上的扩展,其中元素是 Swift 中的通用结构

c# - 从 aspx 页面上的 URL 获取参数

c++ - 这些 GCC/G++ 参数是什么?