So let’s say I have a Codable type like so:
struct MyCodable {
let name: String
let value: Int
}
Presumably, the compiler should generate a set of coding keys like so:
enum CodingKeys: String, CodingKey {
case name
case value
}
Is there any way to query these coding keys?
For instance, I would like to be able to do the following:
for key in MyCodable.CodkingKeys.allCases {
print(key)
}
Is this possible?
2
Answers
CodingKeys
enums are generated asprivate
nested types (on purpose), so they can’t be accessed from outside of the type. In your example, if that loop is written outside of theMyCodable
type, it will not work; butMyCodable
does have access to its keys internally.To expose the keys, you will either need to write out the
CodingKeys
enum yourself with a different access modifier (you can offerCodingKeys
without needing to implementinit(from:)
/encode(to:)
yourself), or add a method/property onMyCodable
which exposes the set of coding keys in a way that is appropriate for your use case (e.g.var codingKeys: [CodingKey] { ... }
).The synthesized code looks like this:
Unfortunately, as you can see, it’s
private
and does not conform toCaseIterable
. Alternatively you can do that part manually and access theenum
only inside your struct like so: