Declare a function with variadic arguments

 Problem

I want to declare and call a function which takes a variable number of arguments.



 Recipe


// Declare our function which takes
// a variable number of Integer arguments
func sum(numbers: Int...) -> Int {
    var result = 0
    for number in numbers {
        result += number
    }

    return result
}

// Call it with just 2 parameters
let sum1 = sum(1,2)
print(sum1)

// Call it with even more parameters
let sum2 = sum(1,2,3,4,5,6)
print(sum2)
				

Heard the news?

The Swift Cookbook for Swift 3 is at last here! For iBooks, Kindle and Paperback.
Hurry up - and Check it out! ;-)

 

 Playground