Swift 3 - 比较来自两个不同词典的键值,如果键值匹配

时间:2018-02-04 04:17:25

标签: swift dictionary compare key-value

我有两个词典数组:

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

Dict 2 = 
[{"id":"100", "address":"1 Main Street"}
,{"id":"110", "address":"2 Main Road"}
, {"id":"120", "address":"3 Main Street"}]

我想比较Dict 2中每个词典对Dict 1的键值:值对 id ,如果id匹配,请更新相应的地址来自Dict2中的值的Dict 1。

所以期望的输出应该是:

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

修改

根据要求,这里有关于我如何解析数据的更多信息。我得到Dict1和Dict2作为对HTTP URL调用btw的响应。而且,我在解析时使用[Dictionary]类型的字典。

        let Task1 = URLSession.shared.dataTask(with: URL!) { (Data, response, error) in
            if error != nil {
                print(error)
            } else {
                if let DataContent = Data {
                    do {
                        let JSONresponse1 = try JSONSerialization.jsonObject(with: DataContent, options: JSONSerialization.ReadingOptions.mutableContainers)
                        print(JSONresponse1)

                        for item in JSONresponse1 as! [Dictionary<String, Any>] {
                            //Parse here    
                        }
                    }
                    catch { }
                    DispatchQueue.main.async(execute: {
                        self.getAddressTask()
                    })
                }
            }
        }
        Task1.resume()
    }

JSONResponse1是Dict 1

然后在上面调用的getAddressTask()函数内部,我进行HTTP URL调用以获取Dict 2

    let AddressTask = URLSession.shared.dataTask(with: URL2!) { (Data, response, error) in
        if error != nil {
            print(error)
        } else {
            if let DataContent = Data {
                do {
                    let JSONresponse2 = try JSONSerialization.jsonObject(with: timeRestrictionsDataContent, options: JSONSerialization.ReadingOptions.mutableContainers)
                    print(JSONresponse2)
                        for item in JSONresponse2 as! [Dictionary<String, Any>] {
                            //Parse here    
                        }
                catch { }
                self.compileDictionaries()
            }
        }
    }
    AddressTask.resume()

JSONResponse2是Dict2

在compileDictionaries()中,我想获得所需的输出,如上所示。

1 个答案:

答案 0 :(得分:1)

您应该使用Codable协议构建数据并创建一个更改联系人的变异方法。如果您需要更新联系人数组,只需使用JSONEncoder对联系人进行编码即可:

struct Contact: Codable, CustomStringConvertible {
    let id: String
    var address: String?
    var name: String?
    var phone: String?
    mutating func update(with contact: Contact) {
        address = contact.address ?? address
        name = contact.name ?? name
        phone = contact.phone ?? phone
    }
    var description: String {
        return "ID: \(id)\nName: \(name ?? "")\nPhone: \(phone ?? "")\nAddress: \(address ?? "")\n"
    }
}

游乐场测试:

let json1 = """
[{"id":"100", "name":"Matt", "phone":"0404040404", "address":"TBC"},
{"id":"110", "name":"Sean", "phone":"0404040404", "address":"TBC"},
{"id":"120", "name":"Luke", "phone":"0404040404", "address":"TBC"}]
"""

let json2 = """
[{"id":"100", "address":"1 Main Street"},
{"id":"110", "address":"2 Main Road"},
{"id":"120", "address":"3 Main Street"}]
"""

var contacts: [Contact] = []
var updates: [Contact] = []
do {
    contacts = try JSONDecoder().decode([Contact].self, from: Data(json1.utf8))
    updates = try JSONDecoder().decode([Contact].self, from: Data(json2.utf8))
    for contact in updates {
        if let index = contacts.index(where: {$0.id == contact.id}) {
            contacts[index].update(with: contact)
        } else {
            contacts.append(contact)
        }
    }
    let updatedJSON = try JSONEncoder().encode(contacts)
    print(String(data: updatedJSON, encoding: .utf8) ?? "")
} catch {
    print(error)
}

这将打印:

  

[{“id”:“100”,“phone”:“0404040404”,“name”:“Matt”,“address”:“1 Main   街 “},{” ID “:” 110" , “手机”: “0404040404”, “名”: “肖恩”, “地址”:“2   主要   道 “},{” ID “:” 120" , “手机”: “0404040404”, “名”: “卢克”, “地址”:“3   主街“}]

相关问题