skip to Main Content

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


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

    Login or Signup to reply.
  2. The synthesized code looks like this:

    struct MyCodable: Codable {
        let name: String
        let value: Int
        
        // Synthesized by Codable conformance:
        private enum CodingKeys: String, CodingKey {
            case name
            case value
        }
    }
    
    

    Unfortunately, as you can see, it’s private and does not conform to CaseIterable. Alternatively you can do that part manually and access the enum only inside your struct like so:

    struct MyCodable: Codable {
        let name: String
        let value: Int
        
        private static var allCases: [CodingKeys] {
            return [.name, .value]
        }
        
        func query() {
            for key in Self.allCases {
                print(key)
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search