2016-04-19 21 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} –