Variadic Parameter. Passing Multiple Parameters

How many components does addition have? Two, three, ten? Yes, it has as many as we need.

But how to create a function which will take many parameters? Of course, we can create many functions with different signatures but it doesn’t look like the best solution.

Swift has a Variadic Parameter. It means that we can pass many parameters at the same time to function and it will handle all of them.

Let’s say we have function addition which adds two number as well as two million.

It’s very simple, we need to add to parameter type and it will look like: Int… or String…

So our addition function will have one Variadic Parameter.

func add(_ components: Int…) -> Int {
    
var result: Int = 0
    
for component in components {
        result += component
    }
    
return result
}

Let’s test it.

print(“2 + 3 + 10 = \(add(2, 3, 10))”)
print(“1 + 2 + 3 + 4 + 5 + 6 = \(add(1, 2, 3, 4, 5, 6))”)

OUTPUT

2 + 3 + 10 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21