[swift-users] Confused/Surprised by IndexingIterator.forEach behavior
Travis Griggs
travisgriggs at gmail.com
Wed Dec 28 12:57:46 CST 2016
The behavior of the following playground snippet surprised me:
var source = [10, 20, 30, 40]
var stream = source.makeIterator()
stream.next() // 10
stream.next() // 20
stream.forEach { (each) in
print("\(each)")
} // prints 30, 40 to the console
stream.next() // 30
stream.next() // 40
stream.next() // nil
I can move the forEach statement up and down the stack there, and it *appears* that while it respects the the current position of the stream/iterator as a start point, it does not actually consume the elements (as next does). That seems inconsistent to me I guess. I would have expected the forEach to either pass through to the source and just ignore the current position, or to consume the items. Whereas the current behavior is kind of a hybrid.
Guess I’m just looking for some enlightenment as to why it was designed to work this way. I figure there’s some valuable insight here that I’m missing.
More information about the swift-users
mailing list