The difference, it turns out, has to do with how variables are bound in loops, and how values are captured in anonymous functions. The Swift (and Objective-C) behavior – which I was most used to at the time of writing – was to bind
ias a different immutable value in each loop iteration, then capture a reference to that value each time through.
Go, on the other hand, binds a single mutable value for the entire loop, then captures a reference to that single variable instead, only getting the value in question at the time the function is executed.
Interestingly enough, we can even “introduce” this bug in Swift code by using a C-like loop instead of the nicer
insyntax[…] Since this style explicitly uses a single mutable
ifor the entire loop, rather than binding a new
ifor each iteration, the “buggy” behavior – printing five sixes – occurs. Swift is even kind enough to make the mutability of
ihere more explicit, by requiring it be annotated
varin the loop declaration.
Stay up-to-date by subscribing to the Comments RSS Feed for this post.