How to create your own Encoder/Decoder in Swift: The Single Value Container
I wish this article existed when I had to write my own Encoder/Decoder that would have saved me a lot of headaches. Apple’s documentation on the subject is pretty much none existent and when desperately looking online for tutorials the best attempt I could find was that of the Flight School
Guide to Swift Codable. Although a fantastic (free) guide on Codable, it still didn’t give me a good grasp on the full concept.
This article is my attempt to explain how you can write your own Encoder/Decoder and I will do this by taking your hand and walking you through it step-by-step.
Disclaimer: This is not meant as a best practice guide. It is meant as a guide that will teach you about the building blocks so you have a good understanding how everything works and afterwards you can make the decisions that make the most sense for your implementation.
Throughout this article I will follow the same conventions that Apple uses in JSONEncoder/Decoder. Such as using a class for the Encoder/Decoder and making the implementations private.
Building Our First Encoder
We are going to make the simplest most stripped down encoder that I can think of. Our encoder will take a string value and it…