Ad
Error Decoding Data With Codable Even Though Parameters Are Optional
I have the following struct
:
struct Recipe: Codable {
@DocumentID var id: String?
var minutes: Int?
init(id: String, minutes: Int) {
self.id = id
self.minutes = minutes
}
init(from decoder: Decoder) throws {
enum DecodingKeys: CodingKey {
case minutes
}
let container = try decoder.container(keyedBy: DecodingKeys.self)
minutes = try container.decode(Int.self, forKey: .minutes)
}
}
I'm decoding from a source where minutes
is null, so I get the following error message:
Error parsing response data: keyNotFound(DecodingKeys(stringValue: "minutes", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key DecodingKeys(stringValue: \"minutes\", intValue: nil) (\"minutes\").", underlyingError: nil))
However, I thought marking minutes
as optional in struct Recipe
was sufficient to handle this case? Is there something else I need to implement?
Ad
Answer
When you implement init(from:)
manually you need to use the decodeIfPresent(_:forKey:)
variant for optional properties. The decode(_:forKey:)
method throws an error if a nullable field in the JSON data is absent whereas the decodeIfPresent(_:forKey:)
method just returns nil.
Try this:
init(from decoder: Decoder) throws {
enum DecodingKeys: CodingKey {
case minutes
}
let container = try decoder.container(keyedBy: DecodingKeys.self)
minutes = try container.decodeIfPresent(Int.self, forKey: .minutes)
}
Ad
source: stackoverflow.com
Related Questions
- → Function Undefined in Axios promise
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Click to navigate on mobile devices
- → Playing Video - Server is not correctly configured - 12939
- → How to allow api access to android or ios app only(laravel)?
- → Axios array map callback
- → Access the Camera and CameraRoll on Android using React Native?
- → Update React [Native] View on Day Change
- → Shopify iOS SDK - issue converting BuyProductVariant to BuyProduct
- → BigCommerce and shopify API
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → React Native - Differences between Android and IOS
- → What is the difference between React Native and React?
Ad