Swift – SequenceType & GeneratorType with GeneratorOf

In my previous post, we created a custom collection that could be looped with a for-in using Swift’s SequenceType & GeneratorType protocols. The code in that post had a lot of duplication as mentioned. In this post, we will go through how we can refactor that example to make it concise.

The code from the previous post

LibraryGenerator and LibrarySequence both have duplicate init methods taking the same parameter i.e. Library. Also both have a “library” variable, which is redundant.

Before we start refactoring, lets look at the Swift struct, “GeneratorOf”.

The GeneratorOf struct implements the GeneratorType protocol and also has an init method that takes a “next” function needed by the GeneratorType protocol. Using GeneratorOf, we can get rid of our LibraryGenerator class and get away with having just the LibrarySequence. The resulting Library Sequence is as follows:

I also don’t see a real need for a separate Library class and LibrarySequence anymore. Instead lets move the array container for books inside the sequence, change the init method of LibrarySequence to take in array of books, change the generate method to use array count (i.e. books.count) instead of numberOfBooks and finally rename the LibrarySequence to Library. The resulting Library is as follows

We can loop through the library using the following code.