Ios NSDictionary-堆叠相同的id';将元素插入另一个字典
我有一本字典,这本字典的值如下: 编辑:不是json,而是直接编辑字典Ios NSDictionary-堆叠相同的id';将元素插入另一个字典,ios,arrays,swift,xcode,nsdictionary,Ios,Arrays,Swift,Xcode,Nsdictionary,我有一本字典,这本字典的值如下: 编辑:不是json,而是直接编辑字典 [{ "personel_id" = 23; "task_id" = 125; }, { "personel_id" = 34; "task_id" = 125; }, { "personel_id" = 40; "task_id" = 126; }] 我想将具有相同任务id的任务组合成2d数组或字典-我不知道哪一个更好-哪一个会像 { "personel_id" = {
[{
"personel_id" = 23;
"task_id" = 125;
}, {
"personel_id" = 34;
"task_id" = 125;
}, {
"personel_id" = 40;
"task_id" = 126;
}]
我想将具有相同任务id的任务组合成2d数组或字典-我不知道哪一个更好-哪一个会像
{
"personel_id" = {23,34};
"task_id" = 125
}
{
"personel_id" = 40;
"task_id" = 126;
}
或
到目前为止,我在互联网上已经尝试了很多东西,但都无法管理。试试看
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode([Root].self, from: date)
let grouped = Dictionary(grouping: res, by: { $0.taskId })
最后,我找到了答案,那就是:
let groupedDictionary = Dictionary(grouping: self.myDictionary) {
(personel) -> String in
return personel.value(forKey: "task_id") as! String
}
我使用了分组功能,效果很好。请说明您尝试了什么。大多数都是断章取义的,这就是我无法管理它的原因。
.keyDecodingStrategy=.convertFromSnakeCase
,很酷,这一点从未有过!
struct Root : Codable {
let personalId, taskId : Int
}
let groupedDictionary = Dictionary(grouping: self.myDictionary) {
(personel) -> String in
return personel.value(forKey: "task_id") as! String
}