Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??
like image 297
Chris Avatar asked Dec 04 '25 09:12

Chris


2 Answers

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)
like image 92
Dharmesh Kheni Avatar answered Dec 05 '25 23:12

Dharmesh Kheni


(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

like image 41
Eric Qian Avatar answered Dec 05 '25 23:12

Eric Qian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!