Question or problem in the Swift programming language:
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.
Variadic Parameter Approach
func arithmeticMean(numbers: Double...) -> Double { var total: Double = 0 for value in numbers { total += value } return total / Double(numbers.count) } arithmeticMean(5, 10, 15)
Array Parameter Approach
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.
How to solve the problem:
I think there is no speed difference.Because,inside the function,you use Variadic Parameter
just as Array
.
-
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.
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