Variadic Parameters vs Array Parameters in Swift
Image via Author

Variadic Parameters vs Array Parameters in Swift

After I published my previous article on the topic of variadic parameters, the lovely Melisa De la Garza asked me this all-important question...

What's the difference or benefit over using a regular array?

Thinking this is something other people may have wondered, I decided to write out the reply as a stand-alone post so that I could go into more detail.

Let’s start by understanding the difference…


The Variadic Parameter

func shoppingList(items: String...) {
    
    for i in items {
        print(i)
    }
}

shoppingList(items: "milk", "bread", "butter", "jam")

//milk
//bread
//butter
//jam        

Here, I’ve got a function named shoppingList() with a variadic parameter of type String. In the body of the function, there’s a for-loop that loops through the variadic parameter of items and prints each item.

When I call the function with four values, Swift turns my variadic values into the array of items.


The Array Parameter

func shoppingList(items: [String]) {
    
    for i in items {
        print(i)
    }
}

shoppingList(items: ["milk", "bread", "butter", "jam"])

//milk
//bread
//butter
//jam        

The array parameter function works exactly like the variadic parameter function, but in this case, I’ve explicitly declared the parameter to be an array of type String. When I call the function, I pass in an array with four values.

Although both parameters are declared differently, the result is exactly the same, an array that prints the same four values.


What’s the Benefit of Variadic Parameters?

The honest answer is that it depends. variadic parameters provides a nice syntactic sugar for times when the data you’re passing is quite small. It’s also more convenient because Swift is creating the array and our code is free from unnecessary faff.

However, if you’re working with a long list, then it’s best to use an array parameter, that way you can assign the array to a variable and then pass the variable name to the function.

Whichever you decide, make sure you’re not passing a HUGE list of items as a parameter because that will ultimately lead to messy code.

To view or add a comment, sign in

More articles by Ijeoma Nelson

Insights from the community

Others also viewed

Explore topics