【发布时间】:2018-02-04 11:21:34
【问题描述】:
我有一个字典数组,作为对 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"}]
请注意,JSONResponse2 中并不总是存在所有“id”,在这种情况下,我想保持原样
这是我的尝试:
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 循环重复。有什么办法吗?
【问题讨论】:
-
我的建议有用吗?
-
感谢米兰,但我做了一点改动。在这两种情况下,我都附加到 self.finalDictionary 以便获得一个更新的“响应”。您的解决方案创建了两个单独的更新“响应”。但是您建议使用新循环是正确的!谢谢:)
标签: ios dictionary for-loop swift3 compare