2015-10-15 19 views
4

Swift爲我們提供了許多新的功能,例如(最後!)連接字符串和數組。但不支持字典。連接字典的唯一方法是爲它們重載+操作嗎?在Swift中連接兩個字典

let string = "Hello" + "World" // "HelloWorld" 
let array = ["Hello"] + ["World"] // ["Hello", "World"] 
let dict = ["1" : "Hello"] + ["2" : "World"] // error =(
+0

看到這個鏈接可能會對你有所幫助http://stackoverflow.com/questions/30948326/how-to-combine-two-nsdictionary-in-swift –

+2

檢查這個... http://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary –

回答

10

這是不可能的,因爲第二個字典中可能有匹配鍵。但是你可以手動完成,在這種情況下,字典中的值將被替換。

var dict = ["1" : "Hello"] 
let dict2 = ["2" : "World"] 

for key in dict2.keys { 
    dict[key] = dict2[key] 
} 
15

使用方法如下:

  1. 將這個在任何地方,例如詞典+ Extension.swift

    func +<Key, Value> (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] { 
        var result = lhs 
        rhs.forEach{ result[$0] = $1 } 
        return result 
    } 
    
  2. 現在你的代碼只是工作

    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]的結果並不相同。

+0

'+'是一個不錯的選擇:它通常是一個交換操作符,而這個操作符不是。 – Raphael

+0

嘿@Raphael,爲什麼它不可交換?給出兩個字典,你將得到與[[1]:「Hello」] + [「2」:「World」]或[[2]:「World」] + [「1」: 「你好」]' –

+1

@YuchenZhong考慮衝突鍵的情況:'[1:2,2:3] + [2:4,3:5] vs'[2:4,3:5] + [1 :2,2:3]'。 – Raphael