Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Closures in Swift 2 Closure Expressions Closure Expression Shorthand

How do you implement multiple parameter sum function?

I want to implement a closure function that takes in infinite number of parameters and returns the sum.

1 Answer

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

To create a function with a variable number of arguments of type Int, you can use a single parameter, with a type of "Int...". This allows you to input as many arguments of type Int as you want when implementing the function, and stores all those arguments in that parameter as an Array with elements of type Int. To implement this in terms of summing some variable number of Ints and returning the sum:

let sum: (Int...) -> Int = { numbers in
    // numbers IS OF TYPE Array<Int>
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}

sum(1) // 1
sum(1,3) // 4
sum(1,3,5) // 9
sum(1,3,5,7) // 16
sum(1,3,5,7,9) // 25
sum(1,3,5,7,9,11) // 36

I hope this helps!

Thank you!