可变参数v数组参数 [英] Variadic Parameters v Array Parameter

查看:148
本文介绍了可变参数v数组参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难看到在将值传递给函数时使用哪种方法有明显的优势。我的下面的代码可能不是解释我想要做出的决定的最好例子,但我认为这是最容易理解的。

I am struggling to see if there is an obvious advantage over which method to use when passing values into a function. My code below may not be the best example to explain the decision I'm trying to make, but it is my opinion the easiest to understand.

可变参数方法

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

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

Are either of the two techniques preferred? If so, why (speed, reliability or just ease of reading)? Thanks.

推荐答案

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

I think there is no speed difference.Because,inside the function,you use Variadic Parameter just as Array.


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

  1. I think that if the parameters count is small,for example,less than 5,Variadic Parameter may be a better solution,because it is easy to read.

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

If the count of parameters is large. Array is better solution.

也知道, 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.

如果您的函数有一个或多个具有默认值的参数,并且还具有可变参数,请将variadic参数放在所有参数之后列表最后的默认参数。

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.

仅限于我的想法。希望有用

Just from my idea.Hopes helpful

这篇关于可变参数v数组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆