Well, your method returns a closure, which you excute twice.
The closure captures it's environment, in your case the 'outer' variable totalMeters and keeps it's value through different calls.
If this is not what you want, you'd have to put totalMeters into the closure like this:
func runningMetersWithMetersPerDay ( metersPerDay: Int ) -> () ->
Int {
return {
var totalMeters = 0
totalMeters += metersPerDay
return totalMeters
}
}
To answer the question from the comment below:
I've modified the original function and calls, to print out some hints:
func runningMetersWithMetersPerDay ( metersPerDay: Int ) -> () ->
Int {
print ("rMWMD called")
var totalMeters = 0
return {
totalMeters += metersPerDay
print ("calculated new result: \(totalMeters)")
return totalMeters
}
}
print ("start")
var planA = runningMetersWithMetersPerDay (metersPerDay: 2000) // "rMWMPD called"
print ("got planA")
planA() // "calculated new result:2000"
planA() // "calculated new result:4000"
runningMetersWithMetersPerDay (metersPerDay: 2000)() // "calculated new result: 2000"
planA() // "calculated new result:6000"
print ("end")
planA is the result of the function runningMetersWithMetersPerDay (a closure of type (())->Int - take void paramters and return Int) , and you then execute the closure twice and get the results (2000, 4000).
Now, the function runningMetersWithMetersPerDay(metersPerDay:) is called again, returns a new closure and this return value is then excecuted. It returns 2000, since it's a new closure (although not assigned to a variable).
Think of it as the following:
runningMetersWithMetersPerDay (metersPerDay: 2000) /* "rMWMPD called" and now call the closure: */ () // "calculated new result: 2000"
At the end you execute planA a third time, and since it still holds it's own state (e.g. own totalMeters value), it returns 6000.