Swift\'s JSONDecoder offers a dateDecodingStrategy property, which allows us to define how to interpret incoming date strings in accordance with a
It is a little verbose, but more flexible approach: wrap date with another Date class, and implement custom serialize methods for it. For example:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
class MyCustomDate: Codable {
var date: Date
required init?(_ date: Date?) {
if let date = date {
self.date = date
} else {
return nil
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
let string = dateFormatter.string(from: date)
try container.encode(string)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(String.self)
if let date = dateFormatter.date(from: raw) {
self.date = date
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot parse date")
}
}
}
So now you are independent of .dateDecodingStrategy and .dateEncodingStrategy and your MyCustomDate dates will parsed with specified format. Use it in class:
class User: Codable {
var dob: MyCustomDate
}
Instantiate with
user.dob = MyCustomDate(date)