Chris
Chris

Reputation: 471

Swift Closure why does calling function return error?

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??

Upvotes: 3

Views: 218

Answers (2)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

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)

Upvotes: 6

Eric Qian
Eric Qian

Reputation: 2256

(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

Upvotes: 5

Related Questions