Variadic parameters in Swift Closure
Definition
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 closure is called.
Variadic parameters can be used in closures only if we name the variadic parameters. The values passed to a variadic parameter are made available within the closure’s body as an array of the appropriate type. Swift Closures allow only a single variadic parameter ‘…’
Syntax
{ (variadicParameterName: Type…) -> ReturnType in}
Example 1
Following is a closure with a variadic parameter named “numbers” and a type of “Double…” and it is made available within the closure’s body as a constant array called numbers of type [Double]
let mean = { (numbers: Double…) -> Double in var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count)}mean(1.2, 2.3)// Output - 1.75
Example 2
Following is a closure with a variadic parameter named “names” and a type of “String…”
let websiteNames = { (names: String…) in print(names)}websiteNames("Apple", "Medium", "Google")// Output - ["Apple", "Medium", "Google"]