Why does the following fail to compile (getting this for an error: Could not find an overload for '_conversion' that accepts the supplied arguments) when passing in a Int...?
func sumOfNumbers(numbers: Int...) -> Int{
var sum = 0;
for number in numbers{
sum += number
}
return sum
}
func averageOfInts(numbers: Int...) -> Int{
var sumNums: Int = 0
sumNums = sumOfNumbers(numbers)
var count = numbers.count
return sumOfNumbers(numbers)/numbers.count
}
But when a Int[] is used in place of the Int... it compiles and works as expected.
When the type of an argument is Int...
all the subsequent args are bunched into the array for you, whereas Int[]
requires you to pass just one argument, an array of Ints:
func sumOfIntsSplat(numbers:Int...) -> Int {
var sum = 0;
for number in numbers{
sum += number
}
return sum
}
func sumOfIntsArray(numbers: Int[]) -> Int{
var sum = 0;
for number in numbers{
sum += number
}
return sum
}
sumOfIntsSplat(1,2,3,4,5)
sumOfIntsArray([1,2,3,4,5])
The Int...
syntax is referred to as a Variadic parameter in the swift documentation
(aside: I borrowed the name "splat" from coffeescript, where I first encountered this syntax)