我想将字典数组从当前字典重新排列为输出
当前词典
[[1: ["hours": 4.0, "projectName": "starworks"]], [1: ["hours": 5.0, "projectName": "starworks"]], [2: ["hours": 7.0, "projectName": "Ada-solo"]] [2: ["hours": 5.0, "projectName": "Ada-solo"]]]
与数组比较
[1,2,3,4,5]
输出愿望
[[1: ["hours": 4.0, "projectName": "starworks"], ["hours": 5.0, "projectName": "starworks"]], [2: ["hours": 7.0, "projectName": "Ada-solo"], ["hours": 5.0, "projectName": "Ada-solo"]]]
答案 0 :(得分:0)
就像Sulthan所说的那样,您可以将字典更改为自定义对象,也可以使用foreach循环遍历字典。
您可以这样做。
var dictArray = [[1: ["hours": 4.0, "projectName": "starworks"]], [1: ["hours": 5.0, "projectName": "starworks"]], [2: ["hours": 7.0, "projectName": "Ada-solo"]],[2: ["hours": 5.0, "projectName": "Ada-solo"]]]
var result = [Int: [[String:Any]]]()
dictArray.forEach { dict in
// 1. Make sure the key/values doe exist.
guard let key = dict.first?.key, let value = dict.first?.value else { return }
// 2. Check for existing data
if var existingData = result[key] {
// 3a. Append the new value
existingData.append(value)
result[key] = existingData
} else {
// 3b. Add the new value
result[key] = [value]
}
}