Swift为我们提供了许多新的功能,例如(最后!)连接字符串和数组。但不支持字典。连接字典的唯一方法是为它们重载+操作吗?在Swift中连接两个字典
let string = "Hello" + "World" // "HelloWorld"
let array = ["Hello"] + ["World"] // ["Hello", "World"]
let dict = ["1" : "Hello"] + ["2" : "World"] // error =(
Swift为我们提供了许多新的功能,例如(最后!)连接字符串和数组。但不支持字典。连接字典的唯一方法是为它们重载+操作吗?在Swift中连接两个字典
let string = "Hello" + "World" // "HelloWorld"
let array = ["Hello"] + ["World"] // ["Hello", "World"]
let dict = ["1" : "Hello"] + ["2" : "World"] // error =(
这是不可能的,因为第二个字典中可能有匹配键。但是你可以手动完成,在这种情况下,字典中的值将被替换。
var dict = ["1" : "Hello"]
let dict2 = ["2" : "World"]
for key in dict2.keys {
dict[key] = dict2[key]
}
使用方法如下:
将这个在任何地方,例如词典+ Extension.swift:
func +<Key, Value> (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var result = lhs
rhs.forEach{ result[$0] = $1 }
return result
}
现在你的代码只是工作
let string = "Hello" + "World" // "HelloWorld"
let array = ["Hello"] + ["World"] // ["Hello", "World"]
let dict = ["1" : "Hello"] + ["2" : "World"] // okay =)
编辑:
至于建议@Raphael的+
迹象暗示计算是可交换的。请注意,情况并非如此。例如[2: 3] + [2: 4]
与[2: 4] + [2: 3]
的结果并不相同。
看到这个链接可能会对你有所帮助http://stackoverflow.com/questions/30948326/how-to-combine-two-nsdictionary-in-swift –
检查这个... http://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary –