How to create an Encoder/Decoder: Super Encoder/Decoder

Mark van Wijnen
9 min readJun 26, 2024

This is the six and last 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 super encoders and decoders.

What does Super Encoder do?

The superEncoder method in the context of Swift's Encoder protocol is used to obtain an encoder for the super class when encoding a subclass. This is particularly useful when dealing with inheritance, as it allows you to encode the properties of the superclass separately from those of the subclass.

Imagine you have a box (container) and you want to put another smaller box inside it, but you don’t know what kind of smaller box it will be. superEncoder and superDecoder allow you to reserve a spot inside the big box for the smaller box, even though you don’t know its type yet.

The reserved spot allows the base class to encode its data in its own preferred format, while the subclass can use a different format. This ensures compatibility and correctness in encoding complex data structures.

Super Encoder in Practice

Let’s go through an example in Swift to illustrate how superEncoder and superDecoder might be used in…

--

--

Mark van Wijnen

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