We can send single values or use some type of collection to send several values, however, we also have another little-known or little-used option to send several values.

What are “variadic parameters”

This type of parameter will allow us when calling the function or method to be able to send either one or several values ​​of that same type, but the Swift blog definition reads much better.

A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. docs.swift.org

How to use it

Using this parameter type is as simple as placing 3 dots (…) after the name of the parameter type.

func printNumbers(_ values: Int...) {
    // ...
}

The previous code is a very simple use of this type of parameter, putting these 3 points (…) will allow us to use this function in the following way.

printNumbers(1)

printNumbers(1, 2)

printNumbers(1, 2, 3)

Something important to keep in mind is that this type of parameter inside the function is an array and if you don’t believe me you can check it using the same function above and a print to see the result in the console.

func printNumbers(_ values: Int...) {
  print(values)
}

printNumbers(1, 2, 3) // output: [1, 2, 3]

It doesn’t matter if you send a single value, it will also become an array

printNumbers(1) // output: [1]

We can add more parameters or even just use more than 1 variadic parameter, if the parameter comes next to the variadic parameter it needs to have an argument label so we don’t make mistakes about which arguments are for the variadic parameter and which are for the following parameter.

func players(_ rightSide: String..., leftSide: String...) {
  // do something
}

players("Luis", "John", "Jenny", leftSide: "Kelly", "Mike")

Fun Fact

If you have never used this type of parameter but you have been programming in Swift for a while, chances are you have come across a function that uses them, this is the print function.

We can see in the method signature that its first parameter is a variadic parameter.

func print(_ items: Any..., separator: String = " ", terminator: String = "\n")

Conclusion

In practice, it is not very used and you will see that when we want to pass a collection of values ​​we usually use a collection type such as Array, Set, and even Dictionary.

The reason is that we can easily convert several values ​​to a collection. Still, we can’t make a collection a variadic parameter, so they are best used when you concretely and explicitly know what to pass to the function/method.

I hope this article helps you, I’ll appreciate it if you can share it and #HappyCoding👨‍💻.

References