0

I'm implementing my own JSON encoder/decoder, à la Swift's Encoder & Decoder protocols.

The thing is, I only want to override a small subset of the functionality already provided by JSONEncoder in Foundation. JSONEncoder, contrary to its name, is not an actual Swift Encoder. Instead, it wraps a fileprivate class _JSONEncoder, which implements all the required Encoder functions.

To write my own customized encoder, I could either:

  • Write my own JSON encoder from scratch.
  • Copy-paste and modify _JSONEncoder from the source itself.

Neither are particularly appealing solutions. Writing my own encoder is an arduous and daunting task, and I have no doubt that it will be riddled with bugs. Copy-pasting _JSONEncoder, on the other hand, forces me to awkwardly check and port fixes each time there's an update to the original source file.

I'd rather just have _JSONEncoder exposed, and wrap its Encoder-related functions while injecting my own code as necessary.

Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80
  • Even if that were possible: A private class is an implementation detail of the Foundation library and may change with a new release, which makes your approach fragile. – Martin R Feb 05 '18 at 08:42
  • @MartinR: I understand, and it's an acceptable compromise to me for now. – Vatsal Manot Feb 05 '18 at 08:44
  • You could write a wrapper `Encoder` by making a dummy `Encodable`, passing that off to `JSONEncoder`, and then having your custom encoder wrap the `Encoder` you get back during encoding (related question: https://stackoverflow.com/q/48123983/2976878). – Hamish Feb 05 '18 at 09:31
  • @Hamish: Hadn't thought about that, seems like it could work. Thanks! – Vatsal Manot Feb 05 '18 at 09:34

0 Answers0