How to create an Encoder/Decoder: The (Keyed) Container
17 min readJun 18, 2024
This is the fourth part of the serie. The first part can be found here. This serie explains everything you need to know to start building your own encoder/decoder.
There are three types of containers:
- The singleValueContainer for primitive values such as strings and integers.
- The unkeyedContainer for values without keys such as arrays and sets.
- The (keyed) container for values such as dictionaries, classes and structs.
This article will explain the third and last container: the keyed container.
Encoder
let keyValuePairs = [
"title" : "Winnie-the-Pooh",
"author" : "A. A. Milne",
"illustrator" : "E. H. Shepard"
]
do {
let encoder = MyEncoder()
let encodedString = try encoder.encode(keyValuePairs)
print(encodedString)
// title=Winnie-the-Pooh&author=A. A. Milne&illustrator=E. H. Shepard
} catch {}
The encoder will get a dictionary of keys and values. It will take each key and value pair and stick them together with the
=
symbol. Then it will take all those pairs and stick them together with the&
symbol into one single string.
Build MyEncoder
class MyEncoder {…