Hello everyone.!
I was practicing decoding dates from .json files, and came across a very bizarre problem.
Below are my decode file and my main view file. (These are pretty identical to what we've learned in Moonshot project)
Bundle-Codable.swift
extension Bundle {
func decode<T: Codable> (_ file: String) -> T {
// Find path to the file
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
// load information of the url into data
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle")
}
let decoder = JSONDecoder()
// Decoding "Date" format
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
do {
let loaded = try decoder.decode(T.self, from: data)
return loaded
} catch {
fatalError("Failed to decode \(file) from bundle. Error: \(error)")
}
}
}
ContentView.swift
struct Model: Codable, Identifiable {
let id = UUID()
let date: Date?
var formattedLaunchDate: String {
date?.formatted(date: .abbreviated, time: .omitted) ?? "N/A"
}
}
let dates: [Model] = Bundle.main.decode("sample1.json")
struct ContentView: View {
var body: some View {
VStack {
ForEach (dates) { date in
Text(date.formattedLaunchDate)
}
}
}
}
Now here's where it get's interesting. I have two almost identical json files; one works perefectly fine but the other one throws an error.
sample1.json (WORKS)
[
{
"date": "1951-05-04"
},
{
"date": "1951-05-07"
},
{
"date": "1951-05-08"
}
]
sample2.json (ERROR)
[
{
"date": "1951-05-04"
},
{
"date": "1951-05-06"
},
{
"date": "1951-05-07"
},
{
"date": "1951-05-08"
}
]
As you can see, the only difference between sample1 and sample2 is the addition of "date": "1951-05-06". And naturally, that (index: 1) is where the error occurs.
Error: dataCorrupted(Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "date", intValue: nil)], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil)).
It seems like from a json file with thousands of dates, this happens with around 1 out of 1000 dates.
Any thoughts on why this might happen?