Closures/Value capture: Difference between revisions
Content added Content deleted
(added swift) |
|||
Line 1,040: | Line 1,040: | ||
=={{header|Swift}}== |
=={{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: |
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: |
<lang swift>var funcs: [() -> Int] = [] |
||
for var i = 0; i < 10; i++ { |
for var i = 0; i < 10; i++ { |
||
funcs.append({ i * i }) |
funcs.append({ i * i }) |
||
Line 1,047: | Line 1,047: | ||
However, using a foreach loop over a range does work, since you get a new constant variable every iteration: |
However, using a foreach loop over a range does work, since you get a new constant variable every iteration: |
||
<lang swift>var funcs: |
<lang swift>var funcs: [() -> Int] = [] |
||
for i in 0..10 { |
for i in 0..<10 { |
||
funcs.append({ i * i }) |
funcs.append({ i * i }) |
||
} |
} |
||
Line 1,054: | Line 1,054: | ||
The C-style for loop can also work if we assign it to a local variable inside the loop: |
The C-style for loop can also work if we assign it to a local variable inside the loop: |
||
<lang swift>var funcs: |
<lang swift>var funcs: [() -> Int] = [] |
||
for var i = 0; i < 10; i++ { |
for var i = 0; i < 10; i++ { |
||
let j = i |
let j = i |
||
Line 1,062: | 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: |
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 }} |
<lang swift>let funcs = [] + map(0..<10) {i in { i * i }} |
||
println(funcs[3]()) // prints 9</lang> |
println(funcs[3]()) // prints 9</lang> |
||