Sometimes, it's not possible to list the number of parameters a function could need. Consider a sum
function:
func sum(_ a: Int, _ b: Int) -> Int {
return a + b
}
This works fine for finding the sum of two numbers, but for finding the sum of three we'd have to write another function:
func sum(_ a: Int, _ b: Int, _ c: Int) -> Int {
return a + b + c
}
and one with four parameters would need another one, and so on. Swift makes it possible to define a function with a variable number of parameters using a sequence of three periods: ...
. For example,
func sum(_ numbers: Int...) -> Int {
return numbers.reduce(0, combine: +)
}
Notice how the numbers
parameter, which is variadic, is coalesced into a single Array
of type [Int]
. This is true in general, variadic parameters of type T...
are accessible as a [T]
.
This function can now be called like so:
let a = sum(1, 2) // a == 3
let b = sum(3, 4, 5, 6, 7) // b == 25
A variadic parameter in Swift doesn't have to come at the end of the parameter list, but there can only be one in each function signature.
Sometimes, it's convenient to put a minimum size on the number of parameters. For example, it doesn't really make sense to take the sum
of no values. An easy way to enforce this is by putting some non-variadic required parameters and then adding the variadic parameter after. To make sure that sum
can only be called with at least two parameters, we can write
func sum(_ n1: Int, _ n2: Int, _ numbers: Int...) -> Int {
return numbers.reduce(n1 + n2, combine: +)
}
sum(1, 2) // ok
sum(3, 4, 5, 6, 7) // ok
sum(1) // not ok
sum() // not ok