[英]Using Swift, how can I tell the difference between a boolean and integer value when loading data from a plist?
[英]using key : value after loading dictionary from a plist using swift
我正在Swift中使用Xcode 6。
以编程方式创建字典时,可以按键或值打印出来或创建数组。 从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;
})
尝试访问此已加载字典中的键或元素会返回一条错误消息,指示该字典没有成员...。
我一直找不到任何东西可以解释为什么加载的字典会有所不同或如何访问成员。
您需要打开可选组件。 可选变量是一个变量,可以像保存其他任何变量一样保存值,但是也可以不保存任何值,或者为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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.