我的项目中有以下结构:
struct templateScheduleResponse: Decodable {
let templateScheduleTypes: [scheduleTemplateType]
}
struct scheduleTemplateType: Decodable {
let templateScheduleNames: [templateScheduleName]?
let templateTypeId: String?
let templateTypeName: String
}
struct templateScheduleName: Decodable {
let templateNameId: String?
let templateSchedName: String
}
我想对它进行排序,以便templateScheduleName数组按templateSchedName值排序。
我完全坚持如何做到这一点。
请指点什么? (我刚刚开始学习Structs,如果你不能告诉我的话!)
谢谢!
更新:这是我的JSON数据:
{
templateScheduleTypes = (
{
templateScheduleNames = (
{
templateNameId = "fad562bc-4510-49ea-b841-37a825a2f835";
templateSchedName = "Daily_Intensive";
},
{
templateNameId = "fdeeb79f-6321-4ff6-b1f0-8272a018e73b";
templateSchedName = "Weekly_Full_Log_Directories";
},
{
templateNameId = "84f9800f-da18-44b8-822f-830069dcc594";
templateSchedName = "Weekly_Full";
},
{
templateNameId = "47a6f050-13d7-4bf6-b5db-ab53e0a3aa54";
templateSchedName = "Weekly_Full_Catalog_Two_Weeks";
},
{
templateNameId = "b8ef9577-e871-4d79-8d3a-cfe958c0c3aa";
templateSchedName = "Weekly_Full_Over_WAN";
},
{
templateNameId = "8d507f52-0d74-404e-ad0d-76e6a7a94287";
templateSchedName = "Monthly_Full";
}
);
templateTypeId = "4e73b9ea-71d0-4abd-83c6-7d7b6d45641b";
templateTypeName = datalist;
},
{
templateScheduleNames = (
{
templateNameId = "39386552-45a5-4470-b152-7be00583e767";
templateSchedName = "Scheduled_Exchange_Server";
}
);
templateTypeId = "a7c28240-c187-4f86-818c-efd86fb26c7d";
templateTypeName = MSESE;
},
{
templateScheduleNames = (
{
templateNameId = "0037846c-d1fe-4c8f-8eec-c62681a12a57";
templateSchedName = "Scheduled_Exchange_Single_Mailbox";
}
);
templateTypeId = "9e06f06a-11dc-44b8-97a0-68bd0b45a07a";
templateTypeName = Mailbox;
}
);
}
答案 0 :(得分:2)
您可以进行临时排序,而无需遵守Comparable。如果x是templateScheduleType类型的某个变量:
x.templateScheduleNames.sorted(by: { (lhs, rhs) -> Bool in
return lhs.templateSchedName < rhs.templateSchedName
})
如果要确保数组在构造时就地排序,请在scheduleTemplateType上定义一个init方法,就像在类上一样:
init(scheduleNames: [templateScheduleName], typeID:String?, typeName:String) {
self.templateScheduleNames = scheduleNames.sorted(by: { (lhs, rhs) -> Bool in
return lhs.templateSchedName < rhs.templateSchedName
})
self.templateTypeId = typeID
self.templateTypeName = typeName
}
答案 1 :(得分:1)
首先,结构名称应以大写字符开头。
要回答您的问题,您需要制作TemplateScheduleName
struct TemplateScheduleName: Decodable {
let templateNameId: String?
let templateSchedName: String
}
符合Comparable
extension TemplateScheduleName: Comparable {
static func ==(lhs: TemplateScheduleName, rhs: TemplateScheduleName) -> Bool {
return lhs.templateSchedName == rhs.templateSchedName
}
public static func <(lhs: TemplateScheduleName, rhs: TemplateScheduleName) -> Bool {
return lhs.templateSchedName < rhs.templateSchedName
}
}
现在给出
let list : [TemplateScheduleName] = []
你可以轻松地对其进行排序
let sortedList = list.sorted()