我从plist中的字典加载一个值但是当我将它打印到控制台时,它会打印:可选(星期一标题)而不仅仅是"星期一标题".
如何在打印时摆脱我的值的Optional()?
var plistPath = NSBundle.mainBundle().pathForResource("days", ofType: "plist")
var plistArray = NSArray(contentsOfFile: plistPath!) as NSArray!
for obj: AnyObject in plistArray {
if var dicInfo = obj as? NSDictionary {
let todayTitle: AnyObject? = dicInfo.valueForKey("Title")
println(todayTitle)
}
}
Run Code Online (Sandbox Code Playgroud)
das*_*ght 38
摆脱它的一种方法Optional是使用感叹号:
println(todayTitle!)
Run Code Online (Sandbox Code Playgroud)
但是,只有在您确定值存在的情况下才应该这样做.另一种方法是打开并使用条件,如下所示:
if let theTitle = todayTitle {
println(theTitle)
}
Run Code Online (Sandbox Code Playgroud)
将此程序粘贴到runswiftlang中进行演示:
let todayTitle : String? = "today"
println(todayTitle)
println(todayTitle!)
if let theTitle = todayTitle {
println(theTitle)
}
Run Code Online (Sandbox Code Playgroud)
经过一些尝试,我认为这种方式更好.
(variableName ?? "default value")!
Run Code Online (Sandbox Code Playgroud)
使用??默认值,然后使用!对折可选变量.
这是一个例子,
var a:String? = nil
var b:String? = "Hello"
print("varA = \( (a ?? "variable A is nil.")! )")
print("varB = \( (b ?? "variable B is nil.")! )")
Run Code Online (Sandbox Code Playgroud)
它会打印出来
varA = variable A is nil.
varB = Hello
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19913 次 |
| 最近记录: |