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"
}
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.