Swift – SequenceType & GeneratorType

We are quite used to looping through collections such as arrays / dictionaries using for-in

For e.g.

Now, lets say the details of library are encapsulated. i.e. The UI layer will receive a library object from the data layer and, all we know is that the library object is a collection that supports for-in looping just like an array.

In the data layer the library object could be as follows :

In order for the library to support looping, it needs to implement SequenceType protocol. The definition of SequenceType is.

The key is the generate method, which returns a GeneratorType. Thus we also need to implement the GeneratorType protocol, which is defined as follows:

i.e. we need to implement “next” method, which is used in looping through the library. Lets create a LibraryGenerator class that implements the GeneratorType protocol.

Now that we have the generator, lets go ahead and implement SequenceType protocol and its generate method. A class that implements SequenceType protocol is as follows:

The initializer takes a library object because we need it to create a LibraryGenerator. Once we have a LibrarySequence, we should be able to loop through the sequence using a for-in

There is a lot of code duplication in between LibraryGenerator, LibrarySequence, which I will refactor in my next post to make the above as concise as possible.