Swift Introduction | Functions | Variadic Parameters
Use a variadic parameter when you do not know how many values will be passed to a function.
(argumentName:Type...)
Callers can provide multiple comma-separated values for this parameter. The function receives those values as an array. You can think of a variadic parameter as an array parameter.
func calc(nums:Int...) -> Int {
var total:Int = 0
for num in nums {
total += num
}
return total
}
calc(1,2,3,4,5)
The declaration is:
calc(nums:Int...)
The call is:
calc(1,2,3,4,5)
Multiple values are passed through nums. Inside the function, iterate over them with for.
for num in nums {...
The number of elements in a variadic parameter is not fixed. Processing it with a for statement is the usual approach.