将NSDictionary创建为Int:plist文件的字符串

将NSDictionary创建为Int:plist文件的字符串,dictionary,swift,plist,Dictionary,Swift,Plist,我创建了一个plist文件,其中包含int作为键,字符串作为值。现在我想用它创建一个字典: let path = NSBundle.mainBundle().pathForResource("myPlist", ofType: "plist") let dict = NSDictionary(contentsOfFile: path!) as [Int:String] 。。。但应用程序崩溃了。但是,如果我将其声明为[String:String],它就可以

我创建了一个plist文件,其中包含int作为键,字符串作为值。现在我想用它创建一个字典:

let path = NSBundle.mainBundle().pathForResource("myPlist", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!) as [Int:String]
。。。但应用程序崩溃了。但是,如果我将其声明为[String:String],它就可以工作。但我需要一个int键

我在名单上找不到任何错误


swift中没有从
String
Int
的隐式转换或转换,因此您必须通过声明新字典并通过
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
,而第二个检查值实际上是
字符串