可变参数 v 数组参数

Variadic Parameters v Array Parameter

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

可变参数方法

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])

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

我认为没有速度difference.Because,在函数内部,你使用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.

来自我的 idea.Hopes 帮助