← 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.
Syntax
swift
func functionName(_ params: Type...) {
    // params is an array [Type]
}

functionName(value1, value2, value3)

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
// Define the function `sum` taking `numbers` and returning an Int
func sum(_ numbers: Int...) -> Int {
    // Declare a mutable variable `total`, initialized to `0`
    var total = 0
    // Loop over `numbers`, binding each item to `n`
    for n in numbers {
        total += n
    }
    // Return `total` from this function
    return total
}
// Print `sum(1, 2, 3)` to the console
print(sum(1, 2, 3))
// Print `sum(10, 20, 30, 40)` to the console
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
// Define the function `average` taking `scores` and returning a Double
func average(_ scores: Double...) -> Double {
    // Return `scores.reduce(0, +) / Double(scores.count)` from this function
    return scores.reduce(0, +) / Double(scores.count)
}
// Print `average(80, 90, 70)` to the console
print(average(80, 90, 70))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.