I have a Swift model using Codable, and my backend is inconsistent with date formats:
Sometimes a date comes as ISO8601 string ("2025-09-30T04:00:00Z")
Sometimes as a Unix timestamp (1696036800)
Sometimes as null.
Right now, I’m repeating custom decoding logic in each model:
struct Event: Codable {
let createdAt: Date?
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let string = try? container.decode(String.self),
let date = ISO8601DateFormatter().date(from: string) {
createdAt = date
} else if let timestamp = try? container.decode(Double.self) {
createdAt = Date(timeIntervalSince1970: timestamp)
} else {
createdAt = nil
}
}
}
This works, but it duplicates code across models.
Question: How can I move this decoding logic into a @propertyWrapper, so I can reuse it like this?
struct Event: Codable {
@FlexibleDate var createdAt: Date?
}
/Date(1224043200000)/format to pass Unix timestamps as unambiguous text, at a time when even JavaScript didn't support ISO8601 properly, but by 2012 most people used ISO8601, and by 2015 this became the actual standard.1696036800is an unusual value