How to create your own Encoder/Decoder in Swift: The Unkeyed Container

Mark van Wijnen
11 min readJun 18, 2024

This is the third part of the encoder/decoder serie. The first part can be found here. This serie explains how to build your own Encoder/Decoder.

At this point we know how to create a coder that uses a single value container for simple primitive values, such as strings and integers. In this article we learn how to use values without keys, such as arrays and sets.

Note: I am experimenting with a new writing style in which the focus is the code and my explanation is italic. So you can focus on the bits that interest you. If you want to figure it out on your own you can skip to the full code sections.

Encoder

let strings = ["Winnie-the-Pooh", "Tigger", "Piglet", "Eeyore", "Kanga"]

do {
let encoder = MyEncoder()
let encodedString = try encoder.encode(strings)
print(encodedString)
// hooP-eht-einniW|reggiT|telgiP|eroyeE|agnaK
} catch {}

The encoder will get an Array of String values. It will reverse those strings and join them together into a single string using a pipe symbol for separation.

Build MyEncoder

class MyEncoder {
func encode(_ value: [String]) throws -> String {
let encoder = __MyEncoder()
try value.encode(to…

--

--

Mark van Wijnen

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