Daily iOS
Swift

An iterator of iterators

Given a 'collection of collections' like [[1, 2], [], [3], [4, 5, 6]], how would you design an iterator that hands out elements one at a time in flat order (1, 2, 3, 4, 5, 6)? It has to work directly in for-in.

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

A struct conforming to IteratorProtocol keeps the outer iterator and the current inner iterator as state, and next() pulls the next inner one when the current is exhausted. A Sequence wrapper's makeIterator() gives you for-in support.

Share a question