|
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
|
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.