Sequence and Iterator
Working with collections is one of every-day-tasks for most developers.
Sequence
We are all familiar with collection types. Array
is, probably, the most common way to represent collection of items. We can easily iterate through by using for
loop.
Another Swift collections representations, like Dictionary
, Set
and others has one important thing in common: all of them are adopting Sequence
protocol. We can create custom sequences for very wide range of purposes. It can be either finite or inifinite sequence. For instance, we may need the powers of 2 sequence or similar.
A sequence is a list of values that you can step through one at a time. The most common way to iterate over the elements of a sequence is to use a
for-in
loop
Sequence
protocol has three associated types:
It also has useful methods for getting subsequences and iteration.
The makeIterator() -> Self.Iterator
method returns an iterator over the elements of the sequence. Where Iterator
is a type that provides the sequence’s iteration interface and encapsulates its iteration state.
IteratorProtocol
IteratorProtocol
is a simple protocol, which contains one associated type and one method - next()
Element
is a type of an element generated by self
. next()
returns an element if it exists, otherwise returns nil
.
I will demonstrate Sequence
and Iterator
power by creating some convenience methods for Date
.
Disclaimer: Calendar
and Date
are complex classes (or class clusters). Working with them, you need to take in concideration a lot of boilerplates, like time zone calculations, device locale and other important calculations. This article omits most of them for the sake of brevity. Samples may be far-fetched for the demonstration purposes
Case study: Spanish lessons schedule
Let’s imagine, that we want to learn new language. Spanish, for example. Your professor told you that you will have one lesson each N
days starting from today. But the bad thing – your professor doesn’t want to work on Sundays. So if the lesson is on Sunday, it will be rescheduled to the next day. We want to receive the schedule – Array<Date>
for next M
days.
Before we go
Lets start from adding some convenience functions to Date
. First of all, we will extend Int
with calendarUnit(:)
function. This function returns DateComponents
object depending on given Calendar.Component
. For the sake of convenience, we will add only days
(that’s enough for our example, but you can add the same for all calendar units you need).
Next we will write small Date
extension. For our convenience we will wrap Date
to be able to get the value of the needed Calendar.Component
.
Then we define function +
to have ability to add date components to our NSDate
:
Now we are able to perform calculation like this:
Schedule generator
DateIterator
looks like:
As you see in the code sample above, in some point our generator returns nil
. It is important! If you remove nil
termination, generator will continue to produce values while your computer has free memory.
Another important thing is: if you try to iterate through dg
one more time, it will not work as expected, because the instance of the generator is already exhausted.
We implemented DateIterator
to build a sequence on it.
As you see, sequence code is very simple and understandable. Actually, our Spanish schedule problem is solved :)
Apple guys are smart, and for the most cases you can use AnyIterator. Rewriten with AnyIterator
, our sequence looks like this:
Infinite sequences
Remember, we were afraid to remove nil
termination? This is the time to do it:
If you are using a playground, then you can see an infinite loop right after you hit Cmd+S shortcut. No worries, we can get needed amount of elements from the infinite sequence:
One of the key benefit of infinite sequences is ability to modify all it’s elements according to the rule. For instance, i want first 10 dates of our infinite sequence, but I hate Mondays. So I want to throw Mondays away:
Surprizingly, but this approach will not work, because we have infinite sequence. LazySequence
is the same as Sequence
, with the key difference, that the elements of the result function, such as map
, filter
, e. t. c. are computed on-demand as the result is used. To make sequence lazy use the lazy
property of the sequence:
Voila! We have finite dates sequence without Mondays.
Conclusion
Sequence
and Iterator
are one of the most used protocols. It is correct and elegant solution for dealing with difficult data collections generating and iteration.
Further reading
- Code provided in the article (paste it to the new Playground)
- Apple official documentation for: