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 trialrazmig pulurian
Courses Plus Student 23,889 PointsClosures - Difference between passing in a constant that stores a function, versus passing in a function directly?
When working with closures, is there any real difference between passing in a constant that stores a function into another function, versus passing in a function directly?
For example both of the let statements at the bottom of this code seem to work for me (granted, I need to comment one let statement out in order for the other to work). Is there a difference?
let allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
func isEvenNumber(i: Int) -> Bool{
return i % 2 == 0
}
let ifEven = isEvenNumber
let evenNumbers = allNumbers.filter(isEven)
let evenNumbers = allNumbers.filter(isEvenNumber)
3 Answers
Dylan Shine
17,565 PointsHi Razmig,
Nope, in Swift functions are first class objects, which allows you to assign functions to variables. When you pass in a function to a function, whether you pass in the function object itself, or a variable with a function as its assignment, you're accomplishing the same thing.
Think of it like this simple function:
let number = 1
func myNum(num:Int) -> Int {
return num
}
myNum(1)
// does the exact same thing as
myNum(number)
Antonija Pek
5,819 PointsThen why overcomplicating in videos with this extra code. It is hard to understand as it is.
Andreas Vestergaard
2,639 PointsGreat question. WHY would we store variables as constants?
The whole course does this, with no mention of why it's done...
Andreas Vestergaard
2,639 PointsAndreas Vestergaard
2,639 PointsThanks. Why would you then assign a function to a variable?
Dylan Shine
17,565 PointsDylan Shine
17,565 PointsI just realized the code I attached to my asnwer to completely irrelevant. Anyways, there's a plenty of reasons you might want to store a function inside a variable. For instance passing a function to a decorator function, which extends the passed in functions functionality and returns a new function. That's a mouth full but since functions are first class objects in swift, they can and should be used like another other object such as string it array.