How to create an Encoder/Decoder: The (Keyed) Container

Mark van Wijnen
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:

  1. The singleValueContainer for primitive values such as strings and integers.
  2. The unkeyedContainer for values without keys such as arrays and sets.
  3. 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 {…

--

--

Mark van Wijnen
Mark van Wijnen

Written by Mark van Wijnen

macOS/iPadOS/iOS/watchOS/visionOS developer and SwiftUI enthousiast. “Stay Hungry, Stay Foolish!” — Steve Jobs

No responses yet