Swift functions with variadic parameters

Vinay Hosamane
2 min readJun 19, 2021

--

Recently I came across this variadic parameters in swift methods. For one moment I thought it may be similar to spread operator in ts or js.

Check out swift documentation here.

If you are not aware of spread operator ‘…’ in js then I will add a sample code snippet for that. This spread operator is usually used to expand it’s content inside some new object. We can use any collection, it could be any array or objects with key values pairs. It is most frequently used operator in js. If you find it interesting, please check this link.

spread syntax in js

Let’s come back to swift’s variadic parameters.

Using Variadic parameters, we can make the function to accept zero or more varying number of values of specified type. For this to happen we should mark the function parameter with ‘…’. Internally swift is converting these values to constant array inside the function.

It is useful to keep the code clean and lightweight. Sometimes we don’t have to create array at the source.

Some of the drawbacks are,

  1. We can not pass an array as value to the variadic function parameter. Where most of our codebase involve arrays. We may end up in writing overloading functions where one accepts array as values and the other accepts varying values.
  2. Another major drawback is, I can not give default values to variadic parameters.

If you find this variadic parameters interesting, please check out this filtered swift evolution proposals. There are some interesting proposals coming up for this feature.

Conclusion

I see that variadic parameters may help us to keep the code clean. But it needs some more changes like,

  1. accepting collection as param, which I find the most required one.
  2. giving default values to variadic parameters.

Thank you for reading this article. If you have some more points or any use cases, please mention them in the comments.

Stay safe.

--

--