Decoding and encoding class hierarchies in Swift

A while ago I was implementing (for fun) a chat client to work with a chat server used in teaching in a GUI programming course. The client is implemented with Swift and SwiftUI.

In the GUI programming course, students get the server and a sample console client, both implemented in Java. The goal for the students is to both design and implement a GUI chat application. Learning goals are related to GUI design, usability design and implementation of a GUI in a selected language and GUI framework. The server is accessed over TCP and data format is JSON.

One tricky thing was to figure out how the Swift Codable could handle a class structure with a base class Message, having different types of messages as subclasses. For example, ChatMessage (having the sender, message, timestamp, etc.), a ListChannelsMessage (containing the available channels on the server side to join), et cetera.

The Java console client class diagram, containing the same message classes as the Swift app.

The Swift Codable does not directly and simply bend to this kind of a class hierarchy. I searched the net and found a good basis here, but it didn’t fully show how to do both decoding and encoding with a class structure like I had.

So obviously, for fun, I banged my head against the wall until I got it working. I was supposed to write a blog post about that, but haven’t had the time.

But today someone in Mastodon asked the exact question; how to do something like this. A good motivation for me to actually do something about that! I didn’t want to publish the whole Swift Chat client app, since students are still able to start working on this project, and someone might want to select Swift/SwiftUI as the GUI for their app.

So instead, I extracted the code to show how to use Codable and JSONSerialization together to handle a class hierarchy like this to encode and decode objects to JSON and back. The code is now available as a simple example project in GitHub.

I shared the repository to the Mastodon discussion. What was exciting for me is that one of the core persons in developing the Swift language itself favourited my reply! ?