Swift 3 - 比较后更新字典数组中的 key:value。请协助

Swift 3 - Update key:value in dictionary in an array of dictionaries after comparison. Please assist

我有一组字典,作为对 URL

的 JSON 响应
JSONResponse1 = 
[{"id":"100", "name":"Matt", "phone":"0404040404", "address":"TBC"}
,{"id":"110", "name":"Sean", "phone":"0404040404", "address":"TBC"}
, {"id":"120", "name":"Luke", "phone":"0404040404", "address":"TBC"}]

我有另一个字典数组,作为对另一个 URL

的 JSON 响应
JSONResponse2 = 
[{"id":"100", "address":"1 Main Street"}
, {"id":"120", "address":"3 Main Street"}]

这两个响应都由键 "id" 链接。我想将 JSONResponse2 与 JSONResponse1 进行比较,并更新 JSONResponse1 以显示地址。所以 JSONResponse1 的输出变成:

JSONResponse1 = 
[{"id":"100", "name":"Matt", "phone":"0404040404", "address":"1 Main Street"}
,{"id":"110", "name":"Sean", "phone":"0404040404", "address":"TBC"}
, {"id":"120", "name":"Luke", "phone":"0404040404", "address":"3 Main Street"}]

请注意,所有 "id" 并不总是出现在 JSONResponse2 中,在那种情况下我想保持原样

这是我的尝试:

    for item in JSONResponse2.enumerated() {
        for var items in JSONresponse1 {
            if item.element["id"] == items["id"] {
                let address_correct = item.element["address"] as! String
                items["address"] = address_correct

                self.finalDictionary.append(items)

            } else {
                self.finalDictionary2.append(items)
            }
        }
    }

但这会创建一个非常长的 finalDictionary2,因为 for 循环重复。有什么解决办法吗?

当然会发生,因为内层循环中的else分支,当JSONResponse1中的item不存在于JSONResponse2中时不执行,而当JSONresponse1中的当前item不存在时执行等于来自 JSONresponse2 的当前项 - 这与您想要的完全不同。

删除 else 分支并在其后添加一个新的 for 循环,这将负责查找那些不在 JSONresponse2 中的项目。所以像这样:

for item in JSONResponse2.enumerated() {
    for var items in JSONresponse1 {
        if item.element["id"] == items["id"] {
            let address_correct = item.element["address"] as! String
            items["address"] = address_correct

            self.finalDictionary.append(items)

        }
    }
}

for item in JSONResponse1 {
    if !(JSONresponse2.contains { (item2) -> Bool in
        return item["id"] == item2["id"]
    }) {
        self.finalDictionary2.append(item)
    }
}