Swift 4.1 JSON 到结构然后到不同日期的数组

Swift 4.1 JSON to Struct then to array of distinct dates

我正在调用一个 API returns 一个 JSON 约会结果。示例:

[{"DiarySummary":"Test appointment","DiaryDescription":"Test","DiaryId":"62","EventNo":"","EventTypeId":"","StartDateTime":"07/06/2018 09:00:51","StopDateTime":"07/06/2018 21:00:51","DayHalfDay":"0","AgentGroupName":"DEV","AgentInitials":"AC","AgentId":"5","OwnerShortName":"","OwnerLongName":"","AbsenceTypeDescription":"Working From Home","AbsenceTypeId":"15"}...

我使用解码函数将此映射到代码中的结构:

struct DiaryAppointment: Decodable {
let DiarySummary: String?
let DiaryDescription: String?
let DiaryId: String?
let EventNo: String?
let EventTypeId: String?
let StartDateTime: String?
let StopDateTime: String?
let DayHalfDay: String?
let AgentGroupName: String?
let AgentInitials: String?
let AgentId: String?
let OwnerShortName: String?
let OwnerLongName: String?
let AbsenceTypeDescription: String?
let AbsenceTypeId: String?
}

self.appointments = try JSONDecoder().decode([DiaryAppointment].self, from: data!)

然后在 UICollectionView 中使用 self.appointments 数组。所有这些都工作得很好。但是,我想根据不同的 StartDates 将 collectionView 分成几个部分,每个部分都有一个 header 。

我已经尝试创建一个辅助数组,但是 StartDateTime 在我的 JSON 中的值因此在我的约会数组中是一个字符串而不是日期。我可以遍历约会数组并将 appointment.StartDateTime 的值转换为日期 object 并添加到一个新数组,这应该允许我挑选出不同的日期,但我将无法拆分原来的约会数组,因为值仍然是一个字符串。

是否可以在调用解码时将​​其转换为日期 object?如果没有,我怎样才能实现所需的功能,或者有更好的方法吗?

首先使用CodingKeys获取小写的变量名并声明尽可能多的非可选属性:

struct DiaryAppointment: Decodable {
    private enum CodingKeys: String, CodingKey {
        case diarySummary = "DiarySummary", diaryDescription = "DiaryDescription", diaryId = "DiaryId"
        case eventNo = "EventNo", eventTypeId = "EventTypeId", startDateTime = "StartDateTime"
        case stopDateTime = "StopDateTime", dayHalfDay = "DayHalfDay", agentGroupName = "AgentGroupName"
        case agentInitials = "AgentInitials", agentId = "AgentId", ownerShortName = "OwnerShortName"
        case ownerLongName = "OwnerLongName", absenceTypeDescription = "AbsenceTypeDescription", absenceTypeId = "AbsenceTypeId"
    }
    let diarySummary, diaryDescription, diaryId, eventNo, eventTypeId: String
    let startDateTime, stopDateTime: Date
    let dayHalfDay, agentGroupName, agentInitials, agentId: String
    let ownerShortName, ownerLongName, absenceTypeDescription, absenceTypeId: String
}

startDateTimestopDateTime 声明为 Date 并将 DateFormatter 作为 dateDecodingStrategy

传递
let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(dateFormatter)