Linked Lists in Swift (2)

And here comes my second post in the series about linked lists in Swift. In the first post we have implemented the basics to make our linked list work. Now, let’s make our linked list a little bit more „Swifty“.

To start with it would be very nice if we could iterate over the elements of our linked list in the same manner as that’s common with the other sequence types in Swift, i.e. Arrays or Dictionaries. In fact, that’s not too difficult. First of all we need an iterator which conforms to the IteratorProtocol. It remembers where we are in the sequence and give its next element.

So, what’s the element of our sequence? I prefer to define the node to be the element rather than its value. This has the advantage that we can look at the neighbours of the element while we are iterating. Alternatively we could define the generic type T to be the element type of our iterator and return the value of the current node in „next“:

We have defined our iterator to be a struct as its recommended by Apple. Since our method „next“ is changing properties of its struct (a value type) we have to flag it being „mutating“.

Let’s stick to the first variant. The rest is quite simple. We make our linked list conform to the Sequence protocol and implement the makeIterator method:

That’s it. Now we can loop very elegantly over our linked list:

With the result:


Nice, isn’t it? Another useful feature would be the possibility to create a linked list from some other kind of sequence, e.g. an array. This is done by a special init:

We have to create a (dummy) default init to add further ones. Our new init takes a sequence of generic types T, loops over all elements and appends each element to our list. Very straightforward. Let’s see if it works:

Yes, everything is fine:


The last thing for today is subscripts. An element in an array can be accessed by a subscript and we want to have that in our linked list as well:

This time I decided to return the value of the node and not the node itself. You may choose whatever you prefer. Let’s test that as well:

Yes, that’s also ok:

That’s it for today. Here is the playground of our enhanced linked list.

The next posts of this series will cover the following objectives:

  1. Some more convenience methods
  2. Serialising

So stay tuned.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert