舊陣列字典我想更新與新的字典保存的字典。如果沒有值,則需要將新值附加到字典中。還用字典的新值更新舊的現有值。字典查找字典中的兩個陣列重複鍵更新與新的磁盤陣列字典
老救陣,我有:詞典
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.update 「Alice.png」 到「愛麗絲。 png「爲」id「= 1,
2.ignore」id「= 2,因爲兩個字符串都是相同的,
3.將newDict中的所有新項添加到savedDict
最終字典應該是:
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
}
}
}
}
我只是想改寫這個字典,新的,所以我更新[ 「ID」: 「1」, 「PIC」: 「Alice.png」 ......爲[ 「ID」: 「1」, 「PIC」: 「alice.png」 ......但是這是行不通的:
savedDict[dict1] = dict2
你應該創建自定義'類'而不是像這樣的字典。之後,一切都會容易得多。 – JuicyFruit
自定義類是什麼樣的? – Brian
檢查我的答案 – JuicyFruit