簡體   English   中英

使用基於日期的Codable協議對從API接收的數據進行排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM