How do I use custom Codable strategies for dates and keys?

Custom Codable, Swift, Dates, Codable Strategies
Learn how to implement custom Codable strategies for handling dates and keys in Swift.
// Swift Code Example import Foundation struct Event: Codable { var name: String var date: Date enum CodingKeys: String, CodingKey { case name case date = "event_date" // Custom key mapping } // Custom date formatting strategy struct DateAdapter: Codable { let dateFormatter: DateFormatter init() { dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" // Set your preferred date format } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(dateFormatter.string(from: date)) } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let dateString = try container.decode(String.self) guard let date = dateFormatter.date(from: dateString) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date format") } self.date = date } } } // Usage let jsonString = "{\"name\": \"Swift Conference\", \"event_date\": \"2023-10-20T10:00:00Z\"}" let jsonData = jsonString.data(using: .utf8)! let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(DateFormatter()) // Use the custom date format let event = try! decoder.decode(Event.self, from: jsonData) print(event)

Custom Codable Swift Dates Codable Strategies