How to create an Encoder/Decoder: The Nested Containers

Mark van Wijnen
10 min readJun 26, 2024

This is the fifth 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.

This article will talk about the Coding Path and Nested Containers.

When to Use Nested Containers?

nestedContainer and nestedUnkeyedContainer are only triggered when a type specifically requests them in order to encode or decode nested data.

In most cases there is no need for it, especially if all the nested types conform to the Codable protocol. Not using nested containers will leverage the automatic synthesis provided by the Codable protocol, making your code more concise and easier to manage.

However, there are some cases when types may want to use nested containers:

  • Custom Encoding/Decoding Logic: If you need to apply custom logic during encoding or handle special cases that automatic synthesis can’t cover, manual encoding/decoding gives you full control over the process.
  • Data Transformation: When your data needs to be transformed or validated before encoding/decoding, manually creating nested containers allow you to perform these transformations explicitly.
  • Non-Standard Structures: If…

--

--

Mark van Wijnen

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