Dealing with key-based polymorphic JSON in Swift Codables

I’ve been trying to use Swift’s Codable protocol with some data I wanted to decode over the wire. Codable makes it easy to serialize things in Swift. Unfortunately, the schema of the protocol I was using doesn’t cleanly map to something easily represented in Swift. It consists of a single object, with a single key, and the key’s name determining its value and type. For example, various JSON blobs:

{"Chat": {"message": "Hello world!"}}
{"Error": {"message": "Invalid request"}}
{"Hello": {"username": "alice", "version": "1.0"}}
/* there are more, but we'll stick with this set for the example */

How do we decode this cleanly?

Continue reading