2016-04-19 20 views
0

我想從一個結構數組中創建一個不可變的字典。有沒有辦法直接在語言中做到這一點?我知道這可以通過一個臨時的可變字典完成。swift中不可變的字典初始化

class Foo { 
    let key: Int 
// ... other stuff 
    init(key:Int){ self.key = key } 
} 

let listOfFoos : [Foo] = [] 

var dict = [Int:Foo]() 
for foo in listOfFoos { dict[foo.key] = foo } 
let immutableDict = dict 

,或者使用的NSDictionary如果foo是一個對象

let immutableDict2 : [Int:Foo] = NSDictionary(objects:listOfFoos, forKeys: listOfFoos.map{$0.key}) as! [Int:Foo] 
+0

據我所知,這是做不到的。解決方法是創建一個函數來返回字典。在字典裏面創建一個可變字典,然後返回它 – user1046037

回答

1

雖然斯威夫特目前不具備構建字典繞過一個可變的字典功能,你可以做一個封閉沒有環,像這樣的:

static let listOfFoos : [Foo] = [Foo(1), Foo(2), Foo(3)] 

static let dict = {() -> [Int:Foo] in 
    var res = [Int:Foo]() 
    listOfFoos.forEach({foo in res[foo.key] = foo}) 
    return res 
}() 

這種語法有點棘手,所以這裏是一個簡短的說明:

關閉之後
  • () -> [Int:Foo] { ... }創建一個無參數閉合產生字典[Int:Foo]
  • var res = [Int:Foo]()創建了以後被分配到一個不可變的變量可變字典dict
  • listOfFoos.forEach({foo in res[foo.key] = foo})替換您for
  • ()大括號立即調用閉包,在初始化時產生結果。
+3

爲什麼'縮小',爲什麼不''forEach'?你絕對不會這樣使用'reduce'。 – Sulthan

+0

@Sulthan固定。謝謝! – dasblinkenlight

+0

使用reduce可以更簡潔地編寫:let dict = listOfFoos.reduce([:]){$ 0 [$ 1.key] = $ 1} –