Variadic Parameters
A variadic parameter lets a function accept any number of values of the same type, from zero to as many as you want.
Declaring a Variadic Parameter
Appending ... after a parameter's type allows the caller to pass any number of values of that type, separated by commas.
Example: Declaring a Variadic Parameter
func sum(_ numbers: Int...) -> Int {
var total = 0
for n in numbers {
total += n
}
return total
}
print(sum(1, 2, 3))
print(sum(10, 20, 30, 40))
Login to try C/C++/Java/PHP code in the editor
Variadic Parameters Are Arrays Internally
Inside the function body, a variadic parameter is just a regular array, so all array operations and properties work on it directly.
Example: Variadic Parameters Are Arrays Internally
func average(_ scores: Double...) -> Double {
return scores.reduce(0, +) / Double(scores.count)
}
print(average(80, 90, 70))
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to declare two variadic parameters in the same function; Swift only allows one variadic parameter per function.
- Forgetting that a variadic parameter is received inside the function as a plain array of its type.
- Placing a variadic parameter before other parameters without a label on the following ones, which can create ambiguity Swift disallows.
Chapter Summary
- A variadic parameter accepts zero or more values, written as
Type.... - Inside the function, a variadic parameter behaves like an array of that type.
- A function may have at most one variadic parameter.
- Callers simply list values separated by commas -- no array brackets needed.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: