Variadic Functions in Swift

What is a variadic function?

Jesus Bernal
The Startup
1 min readJul 15, 2020

--

A variadic function is simply a function that accepts 0 or more items of the same type.

What uses variadic functions?

If you have ever used the print statement then you have used variadic function. If we click into it’s signature, then we get the following

The print function accepts any amount of items that are of type Any. Which allows us to print multiple object by separating them with a comma.

Let’s make our own variadic function

To do so, we declare the parameter type just like normal and add three periods (…) after it to tell Swift we want to accept any number of this type.

Here is an extension to UIView, that will allow us to add as many views to a view that we want.

Without variadic parameters

With variadic parameters

Hope you enjoyed this short write up but most importantly learned something new!

--

--