Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Swift's for-in loop work?

Tags:

swift

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])
}
like image 408
Alex Avatar asked Mar 20 '26 05:03

Alex


1 Answers

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 the Generator protocol. The program begins executing a loop by calling the next() method on the stream. If the value returned is not None, 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 the for-in statement.

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].

like image 185
jtbandes Avatar answered Mar 21 '26 22:03

jtbandes