[英]Sort data received from API using Codable protocol based on date
I'm parsing data from JSON using codable and using my completion handler to pass the data to its origin. 我正在使用codable从JSON解析数据并使用我的完成处理程序将数据传递给它的原点。 However, before passing the caller, I would like to sort data and then send it.
但是,在通过调用者之前,我想对数据进行排序然后发送它。 Below is my code
以下是我的代码
func getEmployeeData(for type: Employee, completion: @escaping (Result<EmployeesBase, APIError>) -> Void) {
//set API endpoint for Employer
let endpoint = type
//Create Request with headers
let request = endpoint.mutableRequest
//get employee Data
fetch(with: request, decode: { json -> EmployeesBase? in
guard let jsonResponse = json as? EmployeesBase else { return nil }
return jsonResponse
}, completion: completion) //Sort this completion by joiningDate
}
struct EmployeesBase: Codable {
let employee: [Employee]
}
struct Employee: Codable {
let name: String
let empID: String
let joiningDate: String
let dept: String
}
I'm confused how I can sort this. 我很困惑如何对此进行排序。
You can do 你可以做
jsonResponse.employee.sort { $0.joiningDate < $1.joiningDate }
struct EmployeesBase: Codable {
var employee: [Employee] // make it var , as sort is mutating
}
let joiningDate: Date // parse this key as Date with correct format
Alter the decoder for this 改变解码器
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" // change to your format
decoder.dateDecodingStrategy = .formatted(formatter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.