NSDictionary - 将相同的 id'ed 元素堆叠到另一个字典中
NSDictionary - stacking same id'ed elements into another Dictionary
我有一本字典,这本字典的值如下:
编辑:不是json,直接是字典
[{
"personel_id" = 23;
"task_id" = 125;
}, {
"personel_id" = 34;
"task_id" = 125;
}, {
"personel_id" = 40;
"task_id" = 126;
}]
我想将具有相同 task_id 的那些分组到二维数组或字典中 - 我不知道哪个更好 - 就像
{
"personel_id" = {23,34};
"task_id" = 125
}
{
"personel_id" = 40;
"task_id" = 126;
}
或
125 = {23,34}
126 = {40}
我已经尝试了很多我在互联网上找到的东西,但无法做到。
尝试
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode([Root].self, from: date)
let grouped = Dictionary(grouping: res, by: { [=10=].taskId })
struct Root : Codable {
let personalId, taskId : Int
}
最后,我找到了答案:
let groupedDictionary = Dictionary(grouping: self.myDictionary) {
(personel) -> String in
return personel.value(forKey: "task_id") as! String
}
我使用了分组功能,效果很好。
我有一本字典,这本字典的值如下:
编辑:不是json,直接是字典
[{
"personel_id" = 23;
"task_id" = 125;
}, {
"personel_id" = 34;
"task_id" = 125;
}, {
"personel_id" = 40;
"task_id" = 126;
}]
我想将具有相同 task_id 的那些分组到二维数组或字典中 - 我不知道哪个更好 - 就像
{
"personel_id" = {23,34};
"task_id" = 125
}
{
"personel_id" = 40;
"task_id" = 126;
}
或
125 = {23,34}
126 = {40}
我已经尝试了很多我在互联网上找到的东西,但无法做到。
尝试
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode([Root].self, from: date)
let grouped = Dictionary(grouping: res, by: { [=10=].taskId })
struct Root : Codable {
let personalId, taskId : Int
}
最后,我找到了答案:
let groupedDictionary = Dictionary(grouping: self.myDictionary) {
(personel) -> String in
return personel.value(forKey: "task_id") as! String
}
我使用了分组功能,效果很好。