2

I am creating a custom JSON decoding method for my struct and I need to loop over all its parameters. I thought about using CodingKeys but I dont know how to achieve it ( or even if it is feasible ).

Here is the code I am trying to reduce :

struct Root: Codable {

    let objectA: ObjectA?
    let objectB: ObjectB?

    enum CodingKeys: String, CodingKey {
        case objectA
        case objectB
    }

    init(from decoder: Decoder) throws {
        objectA = decodeOrSkip(using: decoder, key: .objectA)
        objectB = decodeOrSkip(using: decoder, key: .objectB)
        // ...
    }

    private func decodeOrSkip<T: Codable>(using decoder: Decoder, key: CodingKeys) -> T? {
        guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return nil }
        if let decoded = try? container.decode(T.self, forKey: key) {
            return decoded
        } else {
            log.warning("Unable to decode \(T.self) from \(String(describing: self))")
            return nil
        }
    }
}

struct ObjectA: Codable { /*...*/ }
struct ObjectB: Codable { /*...*/ }

if I could use CodingKeys to access the a value of a variable of a struct, I could loop over my CodingKeys (by making it conform to CaseIterable) and apply decodeOrSkip for each of them


During my researches I found this post : Swift Keypath from String that states :

Finally I found out that I should use CodingKeys instead of KeyPaths to access the a value of a variable of a struct by String

But no code is shown on how to achieve it.

Olympiloutre
  • 2,268
  • 3
  • 28
  • 38
  • 1
    Why can’t you just do `objectA = try? container.decode(ObjectA.self, forKey: .objectA)`? – Steven0351 Jul 25 '19 at 02:09
  • I could totaly! but the problem remains the same, how can I loop over all my `objectX` using `CodingKeys` ? – Olympiloutre Jul 25 '19 at 02:12
  • You can’t access Swift struct member variables via Strings. You could possibly do something similar with the Mirror API in the standard library: https://developer.apple.com/documentation/swift/mirror but you won’t be using strings to access anything. – Steven0351 Jul 25 '19 at 02:23

0 Answers0