Variadic Parameters

A variadic parameter is used to pass an unknown number of parameters to a function. You use three dots after the type to mark a parameter as variadic. This parameter is considered to be an array in the function body.

For example, this function calculates the sum of the given numbers:

func sum(of numbers: Int...) -> Int { var total = 0

for number in numbers { total += number

}

return total

}

And then you can call the function in this manner:

sum(of: 1, 6, 2, -3)

// > 6

The variadic parameter accepts zero or more elements and there can only be one variadic parameter per function.

results matching ""

    No results matching ""