# Codable with references?

**URL:** <https://forums.swift.org/t/codable-with-references/13885>\
**Category:** Using Swift\
**Tags:** codable\
**Created:** [June 21, 2018, 5:20am UTC](https://forums.swift.org/t/codable-with-references/13885 "2018-06-21T05:20:14Z")\
**Posts on this page:** 1\
**Showing post:** 20

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [June 22, 2018, 3:04am UTC](https://forums.swift.org/t/codable-with-references/13885/20 "2018-06-22T03:04:51Z")

</div>

The reason for that is due to the fact that keyed containers are generic on the key type the user requests of them — e.g. `KeyedDecodingContainer<MyType.CodingKeys>`. The issue is that `MyType.CodingKeys` doesn’t have to have a `.super` key, which means that `MyType.CodingKeys(stringValue: “super”, intValue: nil)` returns `nil` in most cases.

A default implementation would have to pass _something_ in to call into `superEncoder(forKey:)`, but there’s very often no key to pass in.

The fact that keyed containers are generic on a key type is mostly a benefit for the API consumer, though — under the hood, the encoder/decoder can do whatever it wants. `JSONEncoder` creates a new `_JSONReferencingEncoder` with the `_JSONKey.super` key, and can do so because [the `_JSONReferencingEncoder` initializer](https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/JSONEncoder.swift#L896) is not generic on a specific key type — it’ll accept any old `CodingKey`.

Note that on decode, things work a little bit differently. `JSONDecoder` has to work around this using a private [`_superDecoder(forKey:)`](https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/JSONEncoder.swift#L1552) which is similarly not generic, and the other generic methods call into it.

---

_[View the full topic](https://forums.swift.org/t/codable-with-references/13885)._
