|
Hi all, I'm running into an issue with my JSON decoder and dates (dates really are hard!). When present in the JSON database, they show up in the format of "2011-04-17". My decoder looks like this:
And my JSON-side struct looks like this:
This all works great when the date appears as above, but crashes and burns when the date that returns is empty, in the form of "". Xcode provides me with this error description: dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "Date", intValue: nil)], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil)) I suspect there is some missing error handling in my decoder for this sort of thing - how can I smartly update my decoder to ignore empty 'date' strings? |
|
@Paul shares a story about a bad date he recently had:
Consider reading the Then in your
See -> More Horrible Date stories |
|
You can also write a custom
|
|
Brilliant, thanks for the help @Obelix and @roosterboy. Posting my updated code in case others find it useful. My updated struct based on @Obelix's suggestions (now featuring an improved naming scheme!):
When called in my real views, I'm structuring it something like this:
I opted to use the "if let" to handle the optional Date? from the struct - this way the view can ignore it if there was an empty string rather than reporting out a default Date.now, or something similar. @roosterboy, you're correct in highlighting a need for a more applicable date formatting strategy...my solution is US-focused and @twostraws would likely recommend I leverage Apple's FormatStyle tool to decode in a way that's more globally applicable. Work to go! |
SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until October 1st.
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.