Jump to content

Closures/Value capture: Difference between revisions

added swift
(Added an alternative Java 8+ solution)
(added swift)
Line 1,037:
Output:
<pre>9</pre>
 
=={{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: (() -> Int)[] = []
for var i = 0; i < 10; i++ {
funcs.append({ i * i })
}
println(funcs[3]()) // prints 100</lang>
 
However, using a foreach loop over a range does work, since you get a new constant variable every iteration:
<lang swift>var funcs: (() -> Int)[] = []
for i in 0..10 {
funcs.append({ i * i })
}
println(funcs[3]()) // prints 9</lang>
 
The C-style for loop can also work if we assign it to a local variable inside the loop:
<lang swift>var funcs: (() -> Int)[] = []
for var i = 0; i < 10; i++ {
let j = i
funcs.append({ j * j })
}
println(funcs[3]()) // prints 9</lang>
 
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>
 
=={{header|Tcl}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.