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 trialRoland Shen
7,628 PointsWhy assign a function to a variable?
What is the point of assigning a function to a variable when you can just call the function in another set of parameters? For example:
func doubler(i: Int) -> Int {
return i * 2
}
let doubled = doubler
var numbers: [Int] = [1,2,3,4,5]
var doubledNumbers = numbers.map(doubled)
Why cant you just write out numbers.map(doubler())? Also, how come no parameters are needed when calling the function?
1 Answer
Gene Osborne
8,630 PointsYou can do exactly that.
Some people like to include extra steps such as this one, so that the code is a little easier to read (a matter of opinion).
You are correct, though, that it is not necessary.
In addition, I feel it is worth mentioning that if you assign the function to a variable, you can use that variable multiple times without calling the method multiple times. This matters for methods that may take a lot of time and/or space to execute. For such methods, minimizing the number of calls to the method may be essential to the program running smoothly.