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 trialDennis Henley
3,421 PointsWhen to use parentheses
In the code under discussion, we create a function within a function.
func printerFunction () -> (Int) -> Void { var runningTotal = 0 func printInteger(number: Int) -> Void { runningTotal += 10 println ("The running total is: (runningTotal)") } return printInteger }
Then we declare a constant of type printerFunction.
let printAndReturnIntegerFunc = printerFunction()
We use parentheses with this declaration.
In a previous example, we created a function as:
func isEvenNumber(i: Int) -> Bool { return i%2 == 0 }
and declared a constant as:
let ifEven = isEvenNumber
This did not require parentheses.
When should we use parenthesis when we make a constant of a function?
3 Answers
nathankrishnan
26,276 PointsDennis, in:
let printAndIntegerFunc = printerFunction()
We are assigning the constant to what printerFunction returns: a function that takes in an int as a parameter and returns void. In other words, we are assigning the execution of the printerFunction to a constant. The execution of the printerFunction returns the inner function: printInteger. That is why this is possible:
printAndReturnIntegerFunc(2)
We are able to pass in the integer value of 2 into the printInteger function, which is the inner function that is invoked when printerFunction is executed.
In
let ifEven = isEvenNumber
The parenthesis aren't used when declaring the function to the constant because we are assigning the function itself, not the execution of the function, to the constant.
Dylan Shine
17,565 PointsHi Dennis,
I don't think I'm going to be able to give you an answer as it relates to your code but the reason we use parentheses is for function/method invocation. If you forget to append the parentheses, you will be return the function object itself, not the functions return value.
Dennis Henley
3,421 PointsNathan,
Thanks. That cleared things up.