// 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)
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?