The value of counter
after your five calls to the incrementCounter
closure will be 5
, but the return of each call to incrementCounter
will seemingly "lag" one step behind. As Sulthan writes in his answer, this is due to x++
being a post-increment operator: the result of the expression will be returned prior to incrementation
var x = 0
print(x++) // 0
print(x) // 1
Also, as I've written in my comment above, you shouldn't use the ++
and --
operators as they will be deprecated in Swift 2.2 and removed in Swift 3. However, if you're interested in the details of post- vs pre-increment operator, you can find good answers here on SO tagged to other languages, but covering the same subject, e.g.
It's worth mentioning, however, a point that is relevant to Swift > 2.1 however, and that don't really relate to the ++
operator specifically.
When you initiate the closure incrementCounter
as
var someOne : Int = 0
let incrementCounter = {
someInt
}
The closure is implictly inferred to be of type () -> Int
: a closure taking zero arguments but with a single return of type Int
.
let incrementCounter: () -> Int = {
return someInt
}
Hence, what you seemingly "see" in you playground is the unused (non-assigned) return value of the call to incrementCounter
closure; i.e., the result of the expression incrementCounter()
.
Whereas the value of counter
is never really printed in the right block of your playground (unless you write a line where the result of that line:s expression is counter
).