Swift Closure Why does the call function return an error?

just learns about the close 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 the function call func have an error, but when I assign func to a constant, there is no error? Where is printAndReturnIntegerFunc (2) passing 2 Int as a parameter for the return value?

printerFunction(2) // error
let printAndReturnIntegerFunc = printerFunction() 
printAndReturnIntegerFunc(2) // no error. where is this 2 going??

      

+3


source to share


2 answers


First of all, you are getting an error here printerFunction(2)

because it printerFunction

cannot accept any arguments, and if you want to give an argument, you can do it like this:

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


}

      

And this will work fine:

printerFunction(2)

      

After that, you reference this function to another variable like this:



let printAndReturnIntegerFunc = printerFunction() 

      

which means the type printAndReturnIntegerFunc

looks like this:

enter image description here

which means it accepts one Int

and it will return void for this to work:

printAndReturnIntegerFunc(2)

      

+6


source


(1) The function signal printerFunction

is equal () -> (Int) -> ()

, which means it takes no parameters and returns another function, so when you try to call printerFunction(2)

with a parameter, you will get an error. (2) And the signature of the return function (Int) -> ()

, which means it takes one Int parameter and returns Void

. So it printAndReturnIntegerFunc(2)

works



+5


source







All Articles