I am using an API to retrieve JSON Data and on occasion the API will give me an empty dictionary when it usually gives me a float or nil If the float is 0.
It seems it is doing this when the value should be nil
How do I handle this? Is there a way so if I am given this empty dictionary value I can just ignore it or return nil or even 0?
Thank you for any and all help!
If you can't change the API (preferred approach), then you can use an enum
with associated values representing each type of result.
So, for the sake of example, let's assume that you get the following two types of results:
Success case:
{ "value": 5.2 }
Failure case:
{ "value": {} }
Then you can decode this with an enum, like so:
enum Result: Decodable {
case success(Float)
case error
enum CodingKeys: CodingKey { case value }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? container.decodeIfPresent(Float.self, forKey: .value) {
self = .success(value)
} else {
self = .error
}
}
}
You can then decode and extract the number:
let result = try JSONDecoder().decode(Result.self, from: json)
if case let .success(value) = result {
print(value) // 5.2
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments