There was some discussion of this in Codable != Archivable - #5 by itaiferber, and specifically:
Not all formats support reference semantics, and one of the things we planned was a way to express whether a given format/encoder supports them or not. JSON, for instance, does not support references natively, so we'd have to add an additional encoding layer on top of JSON to support it.
This is something that's planned, but we didn't have time to push it through in the Swift 4 timeframe.
In the meantime, there are two main approaches you can take to cover your needs:
- If you really want to keep synthesized conformances and make support for this automatic for your format, you can implement an encoder/decoder pair which does the work to implement references. The specifics of how this is done or represented depends on the format you're looking to support; you can look at the implementation of
JSONEncoder
andJSONDecoder
as a basis for how to get started — there isn't an easy template at the moment, but this is something we're also looking into potentially supporting - If you are willing to give up synthesized conformances in order to avoid the work needed to implement an encoder/decoder, you can add your own compatibility layer here — you can create a
ReferenceTable
type (or similar) that you give reference types to; it can give each value (by identity) an identifier which you encode in place of the object. After you've encoded all the UIDs, the last step can be to encode theReferenceTable
itself, which encodes the actual objects you have, once. On decode, you decode theReferenceTable
first, then any object UID types you find can go through the reference table to give you objects back out
Approach #2 is what JSONEncoder
/JSONDecoder
would essentially do on your behalf, but unfortunately, we haven't gotten there yet. If you want to do that yourself at the moment, you'll likely need buy-in from your types, which isn't great.
[If you're interested in following either of these approaches, I can give more concrete information about how to get started/what the process might look like.]