|
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! |
|
Hello everyone, this is my first question in here so if anything is off, please let me know. I'm trying to handle a similar situation like @prburns. But my questions is more about performance.
Thanks in advance. |
|
Decode as String, then Convert to Date: Change the date property in your Result struct to a String?:
Remove the dateDecodingStrategy from the decoder. Access the date property through the computed property:
. Custom Decoding Logic: Create a custom initializer for
|
TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!
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.