iOS Dev Nugget 244 IteratorProtocol


Need to run a code review on your codebase? Hire me

When we write a for-in loop like this:

for each in someCollection {

Swift calls the makeIterator() method on the collection and then make repeated calls next() on the result until it returns nil.

The object returned by the makeIterator() is of a type that conforms to the IteratorProtocol protocol.

You can make use of IteratorProtocol directly. For example, if you might a list of values and you want to be able to pick the next value from the list and perform an action with it. You could implement this using list-like collection, often a FIFO queue. Alternatively, with iterators:

var i = [1, 2, 3].makeIterator() //1 //2 //3 //nil, we are done

Have fun!

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues