Variadic functions — swift
--
In computer programming, a variadic function is a function which accepts a variable number of arguments. The function arguments are represented by … (three period characters) after the argument’s type that can be accessed into their body as an array .
You might have used a print statement in swift. It looks like this:
print(“apple”,”pineapple”,”orange”)
This is a variadic function which accepts parameter of type Any
.
According to apple docs: The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type. For example, a variadic parameter with a name of numbers
and a type of Double...
is made available within the function’s body as a constant array called numbers
of type [Double]
.
Playground code [Example] :
func printFruitNames (_ fruits: String...) -> () {for fruit in fruits { // fruits is a string arrayprint(“\(fruit)”)}}printFruitNames(“apple”,”pineapple”,”orange”)
Note: We cannot have more than one variadic parameter in a function parameter.
If we try to add more than one variadic parameter in a function, the compiler will throw error like (in playground):
Error: only a single variadic parameter ‘…’ is permitted.
The example below calculates the arithmetic mean (also known as the average) for a list of numbers of any length (from apple docs):
func arithmeticMean(_ numbers: Double...) -> Double {var total: Double = 0for number in numbers {total += number}return total / Double(numbers.count)}arithmeticMean(1, 2, 3, 4, 5)// returns 3.0, which is the arithmetic mean of these five numbersarithmeticMean(3, 8.25, 18.75)// returns 10.0, which is the arithmetic mean of these three numbers
Enjoy!!