Search code examples
iosswift4codabledecodableswift4.1

How to use init method in codable when you have model inside?


New in this code world and thanks in advance,

I am getting error

Cannot assign value of type 'String?' to type 'ModalA.ModalC?'

Here is my model class,

struct ModalA: Codable {
    struct ModalB: Codable {
        let value2: String?
        let value3: ModalC?
        private enum CodingKeys: String, CodingKey {
            case value3 = "Any"
            case value2 = "Anything"
        }
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            value2 = try values.decodeIfPresent(String.self, forKey: .value2)
            value3 = try values.decodeIfPresent(String.self, forKey: .value3) // getting error on this line
        }
    }
    struct ModalC: Codable {
        let value3: String?
    }
    let value1: ModalB?
}

How to solve this error?


Solution

  • Your value3 property is of type ModalC, but when decoding you are trying to parse String value (when passing String.self to decodeIfPresent method).

    decodeIfPresent method takes type of decodable value as first argument. In your case decodeIfPresent method returns String value and you are trying to set String value to property of ModalC type.

    So to solve the error you should say that you want to get value of type ModalC for key .value3. To do this you should pass ModalC.self like so:

    value3 = try values.decodeIfPresent(ModalC.self, forKey: .value3)