← Back to Swift Course | Chapter 4: Functions | Lesson 4 of 7

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

markup
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))

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

markup
func average(_ scores: Double...) -> Double {
    return scores.reduce(0, +) / Double(scores.count)
}
print(average(80, 90, 70))
Common Mistakes
  1. Trying to declare two variadic parameters in the same function; Swift only allows one variadic parameter per function.
  2. Forgetting that a variadic parameter is received inside the function as a plain array of its type.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.