0

Given the class:

class ComplementApp: Codable {
    enum TypeCoder: String, Codable {
        case full, singleVal
    }
    var id_spring: String = ""
    var nombre: String = ""
    var typeCoder: TypeCoder = .full
    func encode(to encoder: Encoder) throws {
        switch typeCoder{
        case .singleVal:
            var container = encoder.singleValueContainer()
            try container.encode(id_spring)
        case .full:
            //Here is the bug
            try (self as Encodable).encode(to: encoder)
        }
    }
}

I want to call the default implementation of encode function, but the full case is an infinite loop. I don't want to create CodingKeys, is there some way? Or maybe replicate the default implementation :/.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Why don't you simply declare nombre as optional? `struct ComplementApp: Codable { let idSpring: String let nombre: String? }` – Leo Dabus Feb 13 '20 at 14:07
  • Because this is just one example, I have another class with 20 properties... And I want to implement the same behaviour. – Andre Valdivia Feb 14 '20 at 00:48
  • As long as the properties conform to codable then you do not require coding keys. In addition to this, as long as the property name is the same as the json key, you once again do not need to use coding keys. The encode, decode methods also do not require to be implemented as long as all properties conform to codable. If you just want to decode data to your object then decodable is fine, no encode required. If a property could be nil, then make it optional. The json decoder also has key decoding strategies that also assist you with converting from snakecase. – David Thorn Feb 24 '20 at 17:23

0 Answers0