How do I set up a decodable JSON Struct so that nil values are just skipped?

I am using the following code to save JSON data. However, on occasion, data is presented as nil. Is it possible to ignore this or set a standard value in the event that nil is returned?

struct Information: Decodable {
    
    public let value: Double?
    
    private enum CodingKeys: String, CodingKey {
        case value =  "value"
    }
}

1 answer

  • answered 2021-05-15 18:30 Petr Grigorev

    Declaring custom decoding logic may work in a bad way:

    struct Information: Decodable {
        
        public let value: Double
        
        private enum CodingKeys: String, CodingKey {
            case value =  "value"
        }
    
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            let preValue = try values.decode(Double?.self, forKey: .value)
            value = preValue ?? 0.0
        }
    
    }
    

    For a good one, consider vadian's note