With Java's Stream API it is possible to use functional internal iteration over collections, just like
collection.forEach(out::println)
Is Swift's following for-each loop construct...
for i in names {
println(i)
}
...merely syntactic sugar for an internal (functional) iteration that could also be paraphrased as the following imperative for loop?
for var i = 0; i < names.count; i++ {
println(names[i])
}
The language reference states that for a for-in loop,
The
generate()method is called on the collection expression to obtain a value of a generator type—that is, a type that conforms to theGeneratorprotocol. The program begins executing a loop by calling thenext()method on the stream. If the value returned is notNone, it is assigned to the item pattern, the program executes the statements, and then continues execution at the beginning of the loop. Otherwise, the program does not perform assignment or execute the statements, and it is finished executing thefor-instatement.
So, we can say that
for i in names {
println(i)
}
is roughly equivalent to
var g = names.generate() // "var" because next() is a mutating function
while let i = g.next() { // "let" pattern because next() returns an optional
println(i)
}
As for functional iteration, well, we have SequenceType's func map<T>(_ transform: (Element) -> T) -> [T].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With