【问题标题】:using key : value after loading dictionary from a plist using swift使用 swift 从 plist 加载字典后使用 key : value
【发布时间】:2015-04-04 16:00:43
【问题描述】:

我将 Xcode 6 与 Swift 一起使用。

当我以编程方式创建字典时,我可以按键或值打印出来或创建数组。当我从 plist 创建和加载字典时,我可以总共打印 plist,但不能创建数组或打印键或值。错误消息是“NSDictionary?”没有名为“值”的成员。

我注意到编程字典打印在括号内,键和值之间有一个冒号,但 plist 加载的字典打印在括号内,键和值之间有 = 符号。我认为这可能是问题所在,但不知道为什么以这种方式格式化或如何修复它。

 //  Programmatic Dictionary Code
        var newDict:[String:String] = ["car":"ground", "airplane":"sky", "boat":"water"]

    println("newDict key:value are: \(newDict)")

    //Prints Out as expected
    newDict key:value are: [car: ground, boat: water, airplane: sky]



     // plist read to Dictionary Code
     var type : NSDictionary?

     if let path = NSBundle.mainBundle().pathForResource("transport", ofType:     "plist")   {
     type = NSDictionary(contentsOfFile:path)
     }

     println(type)

    // print out isn't the same as above
    Optional({
        airplane = sky;
        boat = water;
        car = ground;
     })

尝试访问此已加载字典中的键或元素会返回一条错误消息,指示该字典没有成员 ....

我一直找不到任何东西来解释为什么加载的字典会有所不同或如何访问成员。

【问题讨论】:

    标签: ios swift dictionary plist


    【解决方案1】:

    您需要解开您的选项。可选变量是可以像任何其他变量一样保存值的变量,但它也可以根本不保存任何值,或者nil

    这段代码:

    var type : NSDictionary?
    
    if let path = NSBundle.mainBundle().pathForResource("transport", ofType:     "plist")   {
         type = NSDictionary(contentsOfFile:path)
    }
    
    println(type)
    

    应该是:

    var type : NSDictionary?
    
    if let path = NSBundle.mainBundle().pathForResource("transport", ofType:     "plist")   {
         type = NSDictionary(contentsOfFile:path)
    }
    
    println(type!)
    

    无论何时使用type(或任何其他可选),都需要使用!?if let 解包。

    请注意,如果 type 包含 nil 并且您使用 ! 将其解包,您的应用将崩溃,并显示“在解包可选值时意外发现 nil”。

    有关选项的更多信息,请参阅The Swift Programming Language: The Basics

    【讨论】:

    • 这似乎不会改变打印输出或让我将键值识别为成员。它打印为上面的原始帖子,没有括号。大括号和 = 仍然存在。
    • 那是因为newDict 是一个Swift 字典,而type 是一个NSDictionary
    • 感谢您帮助我理解这个问题。有没有办法将 plist 加载到名为 type 的 Swift 字典中?我的研究让我认为这在 Swift 中是不可能的,必须将其加载到 NS 字典中。我的问题是 NS 字典不允许我创建键和值的数组。如果可能的话,我更喜欢 Swift 字典。
    • @radams 您可以将NSDictionary 转换为 Swift 字典,就像您在免费桥接 Foundation 和 CoreFoundation 类型时所做的那样。我将很快编辑我的帖子,展示如何做到这一点;我现在正在使用移动设备。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2017-02-01
    • 2017-10-10
    • 2015-03-25
    相关资源
    最近更新 更多