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 –