The Swift language guide shows you how to create functions that take in variable arguments. It also notes that the arguments are collected into an array.
So if I have the example function sumOf, as noted in the guide:
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
And a second function that also takes a variable number of arguments, how can you pass the same var_args value from the second into the first?
func avgOf(numbers: Int...) -> Int {
// Can't do this without the complier complaining about:
// "error: could not find an overload for '__conversion' that accepts the supplied arguments"
var sum = sumOf(numbers)
var avg = sum / numbers.count
return avg
}
sumOf and averageOf both take a variadic paramter of Int, which is not the same as an Array of Int. The variadic paramter is converted into an Array, though which is what numbers it, but then you aren't able to call sumOf on numbers.
You can fix this by making a sumOf function that takes a variadic parameter and one that takes an arrary like this:
func sumOf(numbers: Int...) -> Int {
return sumOf(numbers)
}
func sumOf(numbers: Int[]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With