Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!