Alamofire 5 and decodable dates - the clean way

While Codable protocol makes a developer’s life easier, it is wired in a specific way by default. When it starts acting on its own and not really parsing the data as we would like, our first reaction would be to give up on it.

I went to length to create private coding keys which would convert to a public computed variable out of the private key. While it keeps the interest of the Struct, it quickly becomes messy.

To my knowledge, the simplest and cleanest way is to make a custom decoder. It helps have a very simple Codable struct and Alamofire 5 request (or any other place you would need to decode some json…). Keep the parsing strategy separate in it’s own file if needed.

struct Event: Codable {
	let title: String
	let startDate: Date
	
	enum CodingKeys: String, CodingKey {
		case title
		case startDate = "date"
	}
}

class CustomDecoder: JSONDecoder {
    let dateFormatter = DateFormatter()

    override init() {
        super.init()
		dateDecodingStrategy = .iso8601
    }
}

AF.request("URL").validate().responseDecodable(of: [Event].self, decoder: CustomDecoder()) { apiResponse in
	switch apiResponse.result {
	case .success(let events):
		print(events)
	case .failure(let error):
		print(error)
	}
}
Tancrede Chazallet