Swift 3-比较来自两个不同词典的密钥值,并在关键值匹配的情况下更新其中一个



我有两个字典数组:

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"}]

我想比较键:value对, id ,在dict 2中的每个字典cit dict 1中的每个字典,如果ID匹配,请在此中更新相应的地址。dict 1来自dict2中的值。

所以所需的输出应该是:

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 call btw的响应。而且,我在解析时使用[字典]类型的字典。

        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((func内部调用,我进行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

compilecticationaries((我想获得如上图所示的所需输出。

您应该使用代码协议构建数据,并创建一种更新联系人的突变方法。如果您需要一旦更新了联系人的数组,则需要使用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","电话":" 0404040404","名称":" Matt","地址":" 1 Main 街道"},{" id":" 110","电话":" 0404040404","名称":" sean","地址":" 2 主要的 路"},{" id":" 120","电话":" 0404040404","名称":" Luke","地址":" 3 大街"}]

相关内容

  • 没有找到相关文章

最新更新