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

查看:21
本文介绍了可变参数 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, in 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])

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

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

推荐答案

我认为没有速度差异.因为,在函数内部,你使用 Variadic Parameter 就像 Array.

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

  1. 我认为如果参数数量很少,例如小于 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 有一些限制:

Also know that,Variadic Parameter have some limitation:

一个函数最多可以有一个可变参数,并且它必须始终出现在参数列表的最后,以避免在调用具有多个参数的函数时产生歧义.

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.

只是我的想法.希望有帮助

Just from my idea.Hopes helpful

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

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