4 ms·
tho I'm not familiar with swift: my guess here is that the first (for ... in) shares a closure / var, so stuff like this classic JS mistake can happen: for
by Groxx 8y ago
tho I'm not familiar with swift: my guess here is that the first (for ... in) shares a closure / var, so stuff like this classic JS mistake can happen:
for i=0;i<10;i++ { setTimeout(() => console.log(i), 100); }
and you get 10 calls logging "9". (most languages I've touched do this, JS just makes it worse since `var x` in the loop will not fix it)
The second won't do that, since the "view" var isn't "mutated" between calls.
- aplummer 8y agoA good try from a JS perspective however: 1) view is immutable in both cases 2) GGP is returning in a void block so both sets of code will fail 3) there is really no difference except iteration vs function calls as far as I can tell, you can iterate arrays and use higher order functions built into arrays... which seems normal 4) you can only access the index in (1) by calling .enumerated() I suppose.
- throw_away2 8y agoI think the difference OP is pointing out is that the return behaves differently. In the forEach, the return exits the closure, but in for-in, it returns from the enclosing function.
- travisgriggs 8y agoyes, this
- delinka 8y agoFirst, to make arguments that rely on syntax, one must use correct syntax. If OP’s syntax were valid, that return in the for-in would indeed exit the closure. To address this argument: the fact that a ‘return’ within a loop exits the enclosing function and a return from within a closure exits the closure is not a Swift problem.