0
0
Swiftprogramming~5 mins

Variadic parameters in Swift

Choose your learning style9 modes available
Introduction

Variadic parameters let you pass any number of values to a function without making many versions of it.

When you want to add many numbers together without fixing how many numbers there are.
When you want to print a list of words or items without knowing how many will come.
When you want to collect many inputs from a user and process them all at once.
When you want to create a function that can handle flexible amounts of data easily.
Syntax
Swift
func functionName(parameterName: Type...) {
    // code using parameterName as an array
}

The three dots ... after the type means the parameter can take many values.

Inside the function, the variadic parameter acts like an array of that type.

Examples
This function greets any number of people by name.
Swift
func greet(names: String...) {
    for name in names {
        print("Hello, \(name)!")
    }
}
This function adds any number of integers and returns the total.
Swift
func sum(numbers: Int...) -> Int {
    var total = 0
    for number in numbers {
        total += number
    }
    return total
}
Sample Program

This program defines a function that prints all scores passed to it. Then it calls the function with four scores.

Swift
func printScores(scores: Int...) {
    print("Scores received:")
    for score in scores {
        print(score)
    }
}

printScores(scores: 85, 90, 78, 92)
OutputSuccess
Important Notes

You can only have one variadic parameter in a function, and it must be last.

Variadic parameters are treated like arrays inside the function, so you can use loops and array methods on them.

Summary

Variadic parameters let functions accept any number of values of the same type.

Use Type... in the function parameter to declare a variadic parameter.

Inside the function, the variadic parameter works like an array.