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?
CodingKeys enums are generated as private 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 the MyCodable type, it will not work; but MyCodable 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 offer CodingKeys without needing to implement init(from:)/encode(to:) yourself), or add a method/property on MyCodable which exposes the set of coding keys in a way that is appropriate for your use case (e.g. var codingKeys: [CodingKey] { ... }).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With