DEV Community

Cover image for Variadic Function in Swift
NalineeR
NalineeR

Posted on

2 1 1 1 1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay