Using Variadic Parameters in Swift
When coding in Swift, there is a function that all developers undeniably call generously and without much thinking, and that is print
. We all use it every day, everywhere; and most of the times, it's our path towards fast and dirty debugging.
Even though print
seems to be winning the battle among the most used commands in Swift, have you ever wondered how it makes it possible to accept an arbitrary number of arguments? And even more, have you ever wanted to implement our own functions that would be acting just like print
?
If so, then the answer to all that is simple and has a name; variadic parameters.
Functions with variadic parameters
A function with a variadic parameter is a function with a parameter that can accept zero, one, or more arguments of the same type. To indicate that a parameter is variadic, all we have to do is to append three dots after the parameter’s data type.
Using the value of a variadic parameter is also pretty straightforward inside a function’s body; we treat it as an array. Take a look at the following example that showcases all that: