Linked Lists in Swift (4)

So, this is my last post in this series about linked lists. There is one last thing we have to add: serialising for storing our linked list on disk or sending over a network. As you have seen in this post, serialising has become much easier in Swift 4. If we make the requirement that our generic class T is already Codable the rest is quite easy.

In all our classes using generics we have to add the constraint of T conforming to the Codable protocol. If T wouldn’t be Codable encoding of our linked list would fail. As mentioned in the previous post the encoding and decoding methods may throw exceptions. So, I have defined an enum for the possible coding error. And we have to define an enum for the coding keys, in our case only with one key. That’s it for the preparation. Now let’s look at the actual encoding part first:

First we have to get an empty container. And then I make our life easy; I just copy our linked list to an array of T and let the encoder encode that. Since Swift knows how to encode collections we’re done already. Simple, isn’t it?

And the decoding part is just the other way round. It’s implemented in another init which gets a decoder. We’ll take the container and let it decode to the array of T. We have to take care if this fails. If everything’s ok we just loop over the array and append the items to our linked list. That’s it.

Now we can test the serialisation of our linked list:

We create a linked list from an array and let it encode by the PropertyListEncoder. The resulting data object we give to a PropertyListDecoder and let it decode to a linked list of strings. Everything works fine:

This was my final post on linked lists in Swift. I hope you’ve enjoyed it. Here is the playground with all the classes and methods.

Schreibe einen Kommentar

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