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.