2014-11-04 73 views
0

我创建了一个包含整数的plist文件作为键字符串作为值。现在我想创建一个字典:创建一个NSDictionary作为Int:String从一个plist文件

let path = NSBundle.mainBundle().pathForResource("myPlist", ofType: "plist") 
let dict = NSDictionary(contentsOfFile: path!) as [Int:String] 

...但应用程序崩溃。然而,如果我声明它是[String:String]它的作品。但我需要密钥作为int。

我无法找到plist内的任何错误。 enter image description here

回答

1

有在迅速Int没有隐式转换或转换从String,所以你必须通过声明一个新的字典,并通过for循环插入元素做手工:

var plist = [Int : String]() 
for (key, value) in dict { 
    if let index = (key as? String)?.toInt() { 
     if let value = value as? String { 
      plist[index] = value 
     } 
    } 
} 

第一if确保该密钥可以转换为Int,而第二个检查该值实际上是String

+0

非常有帮助,再次感谢! – ixany 2014-11-04 16:23:47