I meant to mention that the “clock ticking” iterator above could create an infinite for loop, showing that iterators can let for do anything while can, even the infinite loop. In reality, you’d probably have something like:
let myClock = newClockIterator(tick: 1.0, count: 60) // Tick every second for 1 minute;
for time in myClock {
print("It is now", time)
}
where the iterator has a built-in point where it stops. Sometimes—like this ticking clock, or in traversing a list—the stop point is known in advance, and sometimes—like waiting for a file to download—it isn’t. That used to be the delineation between for and while: if you knew when it would stop before you started, you usually used a for, if not, you used a while. But with iterators, it’s no longer at all so clear—I think it’s actually more common now to say, “use for when you have a ready-made iterator, and use while when you have to do something unusual once—but write your own iterator and then use for if you’re doing something unusual many times”. Writing your own iterators is an intermediate-to-advanced topic, though.
Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags: