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 Swift Closures Functions as First Class Citizens Capturing Variables

Kishan S
Kishan S
15,410 Points

Why do we use parentheses here?

func printerFunction () -> (Int) -> () {
   func printInteger(number:Int)  {
        println("Passed: \(number)")
   }
    return printInteger
}

/////////////////////////////////////////////////////////////////////////////////////////
//   Why do we have to use parentheses here to assign the function to the constant???? //
/////////////////////////////////////////////////////////////////////////////////////////

let printAndIntegerFunc = printerFunction()

And Not Here ??

func printString(aString: String) {
    println("Print String: \(aString)")
}

/////////////////////
//  Why not here?  //
/////////////////////

let someFunction = printString

3 Answers

Kishan Sundar I understand what you mean. Let me first clarify why the parenthesis is used in the printerFunction example.

printerFunction is a function with no parameters, that returns a function that takes in an int as a parameter and returns void. 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 the other example you posted from the video, 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.

Christian Dangaard
Christian Dangaard
3,378 Points

This explanation makes sense, thank you also.

Kishan S
Kishan S
15,410 Points

Why do we have to use parentheses here to assign the function to the constant?? [first code snippet] and Why don't we use parentheses on the [Second code snippet] ??

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

I'm not seeing how Pasan is using parentheses to assign the function to the constant.