使用 key : 使用 swift 从 plist 加载字典后的值

using key : value after loading dictionary from a plist using swift

我正在使用 Xcode 6 和 Swift。

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

我注意到程序化字典打印在括号内,键和值之间有一个冒号,但是 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;
     })

尝试访问此已加载字典中的键或元素returns一条错误消息表明该字典没有成员....

我找不到任何内容来解释为什么加载的词典会不同或如何访问成员。

您需要打开您的可选商品。可选变量是可以像任何其他变量一样保存值的变量,但它也可以根本不保存任何值,或者 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 并且您使用 ! 解包它,您的应用将崩溃,显示 "unexpectedly found nil while unwrapping optional value"。

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