DEV Community

Cover image for Variadic Function in Swift
NalineeR
NalineeR

Posted on

Variadic Function in Swift

The functions which takes Variadic parameter are called Variadic Functions.

Variadic parameters allow us to pass either single or multiple values based on our requirement.

Declaration - You just need to add Three Dots i.e. ... after param data type to make it variadic.

Example - Below function takes an Int as variadic param -

func getSum(values:Int...){
    let sum = values.reduce(0, +)
    print("Sum is-\(sum)")
}
Enter fullscreen mode Exit fullscreen mode

Now let's check how can we call it -
case 1 - Call it with single value -

getSum(values: 8)
Enter fullscreen mode Exit fullscreen mode

case 2 - Call it with multiple values -

getSum(values: 1,7)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sergeyleschev profile image
Sergey Leschev

Being able to pass multiple values to a function using a single parameter can save a lot of time and effort when working with larger datasets or more complex calculations.