Anonymous user
Closures/Value capture: Difference between revisions
→{{header|Swift}}
(added swift) |
|||
Line 1,040:
=={{header|Swift}}==
The naive way using a C-style for loop does not work, since Swift captures variables by reference, and one variable is changed over the course of the loop:
<lang swift>var funcs:
for var i = 0; i < 10; i++ {
funcs.append({ i * i })
Line 1,047:
However, using a foreach loop over a range does work, since you get a new constant variable every iteration:
<lang swift>var funcs:
for i in 0..<10 {
funcs.append({ i * i })
}
Line 1,054:
The C-style for loop can also work if we assign it to a local variable inside the loop:
<lang swift>var funcs:
for var i = 0; i < 10; i++ {
let j = i
Line 1,062:
Alternately, we can also use <code>map()</code> to map over a range, and create the squaring closure inside the mapping closure which has the integer as a parameter:
<lang swift>let funcs = [] + map(0..<10) {i in { i * i }}
println(funcs[3]()) // prints 9</lang>
|