我想用新字典更新保存的字典。如果不存在值,则需要将新值附加到字典中。还使用字典的新值更新旧的现有值。
我有旧保存的字典数组:
var savedDict = [
["id":"1","pic":"Alice.png","name":"Alice Smith","position":"Nurse"],
["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
["id":"12","pic":"bob.png","name":"Bob Smith PhD","position":"Hospital Coordinator"],
]
新下载的字典数组:
let newDict = [
["id":"1","pic":"alice.png","name":"Alice Smith","position":"Nurse"],
["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
["id":"3","pic":"user.png","name":"Dr. Quam","position":"Immunologist"],
["id":"4","pic":"jennifer.jpg","name":"Jennifer Johnson","position":"Case Manager"],
["id":"5","pic":"user.png","name":"John Banks MD","position":"Cardiologist"],
["id":"6","pic":"tammie.png","name":"Tammie Summers","position":"Case Manager"]
]
我想:
1. 将 "Alice.png" 更新为 "alice.png" for "id" = 1,
2.ignore "id" = 2 因为两个字典数组都相同,
3. 附加来自 newDict 的所有新项目进入已保存的字典
最终的字典应该是:
upToDateDict = [
["id":"1","pic":"alice.png","name":"Alice Smith","position":"Nurse"],
["id":"2","pic":"brad.png","name":"Brad Smith MD","position":"Primary Doctor"],
["id":"12","pic":"bob.png","name":"Bob Smith PhD","position":"Hospital Coordinator"],
["id":"3","pic":"user.png","name":"Dr. Quam","position":"Immunologist"],
["id":"4","pic":"jennifer.jpg","name":"Jennifer Johnson","position":"Case Manager"],
["id":"5","pic":"user.png","name":"John Banks MD","position":"Cardiologist"],
["id":"6","pic":"tammie.png","name":"Tammie Summers","position":"Case Manager"]
]
到目前为止我试过这个:
import UIKit
import Foundation
func arrayContains(array:[[String:String]], value:[String:String]) -> Bool {
for item in array {
if item == value {
return true
}
}
return false
}
var upToDateDict = savedDict//Array<Dictionary<String,String>>()
//Save all of the dictionaries from the 1st array (savedDict) that aren't in the 2nd array (newDict)
for item in newDict {
if !arrayContains(array: savedDict, value: item) {
upToDateDict.append(item)
}
}
print(upToDateDict)
//find duplicate keys and check if need to update saved dict with new dict
let key = "id"
for dict1 in savedDict {
if let value = dict1[key] {
for dict2 in newDict {
if dict2[key] == value { //if true duplicate "id" key's found
if dict1 != dict2 { //not duplicate for all keys, so update saved with new dictionary
print("found \(key):\(value) in both arrays")
print("dict1:\(dict1)")
print("dict2:\(dict2)")
savedDict[dict1] = dict2 //what I want to do but will not build
} else {}//all keys duplicate in dict1 and dict2
}
}
}
}
我只想用 new 覆盖这本字典,所以我将 ["id":"1","pic":"Alice.png"... 更新为 ["id":"1","pic":"alice.png"... png"... 但这不起作用:
savedDict[dict1] = dict2