Serialization in Swift

A while ago I tried to make my own (en/de)coder using Codable. Starting from the Encodable protocol seemed a reasonable place to start. I couldn’t figure it out on my own and had to look for a tutorial. Those were like “yeah well, just look at the open source implementation of the JSON coder and copy that”. Seriously?

Everything felt long, verbose and convoluted. All those containers, and functions for every possible type. But hey, those (I.e. you) guys have to consider everything and I just want to encode like 2 types or whatever.

Sometimes I try to recreate a framework (badly) from scratch to improve my skills and understanding (e.g. CoreData, libDispatch). So why not, let’s recreate this for my narrow use case. Use reflection to get a list of all the variables and ... well,.. That might work for encoding but afaict there is no way to create an instance this way.

Using PropertyWrappers to encode things like a custom key seemed a good (or naive?) idea but afaict that information is not exposed via reflection.

Or perhaps something, something with keypaths like Codable but extracting the type out of the keypath type is not possible. So then how does Codable do it? Compiler magic: Ah :bulb:, great :slightly_frowning_face:

While doing all this I went also through the previous related proposals and came across this post by Chris Lattner. It’s about user defined attributes. (That’s kinda meta-programming? Enlighten me if you have spare time.)

It’s a 2 year old post and while some are probably aware of it others might have missed it or forgotten about it.

My point, I guess, is shouldn’t effort and the limited available resources be spend on first improving reflection etc before improving Codable? Improvements of the former will lead to improvements of the latter, won’t it? Or at least it wil/shouldl make improving Codable easier from what I understand.

disclaimer: just a user. Limited compiler knowledge.

3 Likes