Codable Improvements and Refinements

codable

(Chris Lattner) #41

Yes, that approach would make sense.

-Chris


(Karl) #42

So, I think we all want user-defined attributes. There's lots of precedent in other languages and they can be used for some really cool things. On the other hand, if we really want arbitrary, user-defined attributes, we'd need some kind of reflection API to access them.

Personally, I'm not sure that coding-keys belong as part of the model type, particularly when you have some kind of external API and multiple serialisation formats to contend with. I think this is really an Encoder/Decoder-level detail.

I think the best thing would be to create some kind of Schema type which represents how to encode/decode a particular type in a particular format. For example, if you're encoding in to some format which has a native representation for Range, you could choose that schema in place of the JSON-compatible two-unlabelled-values approach.

That's the "Enhanced Contextual Overriding of Encoded Representations" option, basically.


(Trevor Elkins) #43
  1. Can only speak for the annotation-heavy approach here, none of the suggestions I've seen would sacrifice type safety. I'm assuming the implementation would require importing a static annotation type similar to how other languages handle it. See GSON's @SerializedName annotation.

  2. as the two options is extremely clear and easy to teach

    Easy according to you, but that has not been my experience browsing StackOverflow and /r/Swift compared to other approaches. Part of the problem is the locality of the init(from:) and CodingKey abstractions. Users are working at the property-level and suddenly have to shift to implement an initializer or entirely new CodingKey type. A lot of new developers have a hard time making the mental connection.

    From a mile-high view, annotations can be thought of like the decorator pattern, which IMO is a much cleaner and easier abstraction to understand. It's also closely coupled to the actual property that you're working with which reduces the mental load.

Similarly, we don't need bespoke syntax for defining an error domain just to write 20 characters less.

I think that's oversimplifying things a bit. And even so, I'd say it's in the best interest of every language/library to monitor/eliminate boiler-plate code for the sake of self-preservation.