我正在使用可编码的JSON解析数据,并使用我的完成处理程序将数据传递到原始数据。但是,在传递调用者之前,我想先对数据进行排序然后再发送。下面是我的代码
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
}
我很困惑如何分类。
答案 0 :(得分:0)
你可以
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
为此更改解码器
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" // change to your format
decoder.dateDecodingStrategy = .formatted(formatter)