【问题标题】:Swift 3 - Update key:value in dictionary in an array of dictionaries after comparison. Please assistSwift 3 - 比较后更新字典数组中字典中的键:值。请协助
【发布时间】: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


【解决方案1】:

当然会发生,因为内部循环中的else分支,当JSONResponse1中的项目在JSONResponse2中不存在时不会执行,而是在JSONresponse1中的当前项目不等于当前项目时执行来自 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)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多