Swift - Function variable number of parameters


A parameter with a variable number of values is called a variadic parameter.

Swift uses three dots ... to indicate that a parameter has a variable number of values.

Inside the body of the function, the variadic parameter becomes an array:


func sumNumbers(numbers: Int...) -> Int { 
    // in this function,  'numbers' is an array of Ints 
    var total = 0 
    for number in numbers { 
        total += number //from   w w  w.ja va2 s . com
    return total 
var a = sumNumbers(numbers: 1,2,3,4,5,6,7,8,9,10) // 55 


You can only have a single variadic parameter, and any parameter listed after a variadic parameter must have an external parameter name.

Related Topic