当前,我有一个嵌套的字典声明为
var userSchedule = [String:[String:String]]()
我得到如下结果:
["2": ["time": "tbd", "date": "1/15", "name": "Chris"],
"0": ["time": "6:16 PM", "date": "1/15", "name": "Bob"],
"1": ["time": "1:15PM", "date": "1/15", "name": "John"]]
我想对结果进行排序,以便按第一个键对结果进行排序。
所以:
["0": ["time": "6:16 PM", "date": "1/15", "name": "Bob"],
"1": ["time": "1:15PM", "date": "1/15", "name": "John"],
"2": ["time": "tbd", "date": "1/15", "name": "Chris"]]
如何在Swift4中有效地做到这一点?请帮忙!
答案 0 :(得分:0)
Dictionary
是无序的,您无法对其进行排序。
但是,在您的情况下,我将摆脱字典,而只有阵列模型。
创建代表事件的自定义struct
,然后可以根据模型的id
属性对数组进行排序
struct Event {
let time, date, name: String
let id: Int
}
var userSchedule = [Event(time: "tbd", date: "1/15", name: "name", id: 2),
Event(time: "6:16 PM", date: "1/15", name: "Chris", id: 0),
Event(time: "1:15PM", date: "1/15", name: "John", id: 1)]
userSchedule.sort { $0.id < $1.id }
例如,如果您要从服务器获取字典作为响应,则可以使用compactMap
将其重新映射到Event
的数组
struct Event {
let time, date, name: String
let id: Int
}
var userSchedule = ["2": ["time": "tbd", "date": "1/15", "name": "Chris"],
"0": ["time": "6:16 PM", "date": "1/15", "name": "Bob"],
"1": ["time": "1:15PM", "date": "1/15", "name": "John"]]
var schedule = userSchedule.compactMap { (event) -> Event? in
guard let time = event.value["time"], let date = event.value["date"], let name = event.value["name"], let id = Int(event.key) else { return nil }
return Event(time: time, date: date, name: name, id: id)
}
schedule.sort { $0.id < $1.id }
答案 1 :(得分:0)
创建一个结构以保存值并将字典映射到该结构的数组
struct Schedule {
let key: Int?
let time: String?
let date: String?
let name: String?
}
var orderedSchedule = userSchedule.map { Schedule(key: Int($0.key),
time: $0.value["time"],
date: $0.value["date"],
name: $0.value["name"]) }
orderedSchedule.sort { ($0.key ?? 0) < ($1.key ?? 0) }
答案 2 :(得分:0)
您可以这样操作:首先将其排序为一个数组,然后使用字典元素构建一个数组。这很简单,因为它只有两行代码。
var userSchedule = ["2": ["time": "tbd", "date": "1/15", "name": "Chris"],
"0": ["time": "6:16 PM", "date": "1/15", "name": "Bob"],
"1": ["time": "1:15PM", "date": "1/15", "name": "John"]]
let userScheduleArray = userSchedule.sorted{$0.key < $1.key}
print(userScheduleArray)
//[(key: "0", value: ["time": "6:16 PM", "date": "1/15", "name": "Bob"]), (key: "1", value: ["time": "1:15PM", "date": "1/15", "name": "John"]), (key: "2", value: ["time": "tbd", "date": "1/15", "name": "Chris"])]
let separatedDict = userScheduleArray.map{Dictionary(uniqueKeysWithValues: [$0])}
print(separatedDict)
//[["0": ["time": "6:16 PM", "date": "1/15", "name": "Bob"]],
// ["1": ["time": "1:15PM", "date": "1/15", "name": "John"]],
// ["2": ["time": "tbd", "date": "1/15", "name": "Chris"]]]
print(type(of: separatedDict))
//[[String:[String:String]]] i.e. Array<Dictionary<String, Dictionary<String, String>>>