Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to access the coding keys for an automatically generated Codable conformance?

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?

like image 470
sak Avatar asked Oct 18 '25 11:10

sak


1 Answers

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] { ... }).

like image 139
Itai Ferber Avatar answered Oct 21 '25 00:10

Itai Ferber