![](/img/trans.png)
[英]Decode the json in same order as received from the server using Codable protocol
[英]Sort data received from API using Codable protocol based on date
我正在使用codable從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
}
我很困惑如何對此進行排序。
你可以做
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.