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  . jav a2 s.c o m*/
    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