3

just learning about closures and nesting functions. Given the nested function below:

func printerFunction() -> (Int) -> () {
    var runningTotal = 0
    func printInteger(number: Int) {
        runningTotal += 10
        println("The running total is: \(runningTotal)")
    }
    return printInteger
}

Why does calling the func itself have an error, but when I assign the func to a constant have no error? Where is printAndReturnIntegerFunc(2) passing the 2 Int as a parameter to have a return value?

printerFunction(2) // error
let printAndReturnIntegerFunc = printerFunction() 
printAndReturnIntegerFunc(2) // no error. where is this 2 going??
3
  • what kind of error? where it happens? Commented Jun 25, 2015 at 5:28
  • cannot invoke 'printerFunction' with an argument list of type '(Int)' - is the error message. I suppose i'm just basically confused why when I assign printerFunction() to a constant, I can pass variables through the constant but I have no idea where that variable actually gets used in the function itself. Commented Jun 25, 2015 at 5:31
  • 2
    The one-line equivalent of your last two lines is printerFunction()(2). Commented Jun 25, 2015 at 5:37

2 Answers 2

6

First of all you are getting error here printerFunction(2) because printerFunction can not take any argument and If you want to give an argument then you can do it like:

func printerFunction(abc: Int) -> (Int) -> (){


}

And this will work fine:

printerFunction(2)

After that you are giving reference of that function to another variable like this:

let printAndReturnIntegerFunc = printerFunction() 

which means the type of printAndReturnIntegerFunc is like this:

enter image description here

that means It accept one Int and it will return void so this will work:

printAndReturnIntegerFunc(2)
Sign up to request clarification or add additional context in comments.

Comments

5

(1) The function signature of printerFunction is () -> (Int) -> () which means it takes no parameter and returns another function, thats why when you try to call printerFunction(2) with a parameter gives you an Error.
(2) And the signature of the returned function is (Int) -> () which means it takes one parameter of Int and returns Void. So printAndReturnIntegerFunc(2) works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.