如何快速使用包含在字典中

时间:2018-09-29 21:18:08

标签: swift dictionary contains

我写了一个合并两个字典的函子,其中第二个字典覆盖了它们共享相同键的第一个字典

 func merging(_ dict1: [String: String],with dict2: [String: String]) ->
[String: String]{      
    var toreturn : [String : String] = dict1      
    for (key,value) in dict2{    
        toreturn[key] = value
    }   
    return toreturn}

它适用于我所有的测试用例,然后我无法使用contains方法编写它的“哑”版本:

func merging(_ dict1: [String: String],with dict2: [String: String]) ->
[String: String]{
    var toreturn : [String : String] = dict2
    for (key,value) in dict1{
        if(toreturn.contains(where: [key, value]))
    }
    return toreturn}

有人可以帮助我使用contains方法重写功能吗?

1 个答案:

答案 0 :(得分:0)

根据Apple Documentation,您不需要新功能即可合并到Swift中的Dictionary,您只需要使用字典合并方法示例:

let dict1 : [String: String] = ["a" : "1" , "b" : "2"]
let dict2 : [String: String] = ["c" : "3" , "d" : "4"]

let newDict = dict1.merging(dict2) { (current, _) -> String in
    current
}

//newDict values will be : ["a" : "1", "b" : "2", "c" : "3", "d" : "4"]