【问题标题】:Creating a NSDictionary as Int:String out of an plist-file从 plist 文件中创建 NSDictionary 作为 Int:String
【发布时间】:2014-11-04 12:52:48
【问题描述】:

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

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

...但是应用程序崩溃了。但是,如果我将其声明为 [String:String] 它可以工作。但我需要将密钥作为 int。

我在 plist 中找不到任何错误。

【问题讨论】:

    标签: dictionary swift plist


    【解决方案1】:

    在 swift 中没有从 StringInt 的隐式转换或转换,因此您必须通过声明新字典并通过 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多