我从plist中的字典中加载了一个值,但是当我将其打印到控制台时,它会打印:Optional(Monday Title),而不仅仅是“ Monday Title”。
如何在打印时摆脱值的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) } }
摆脱的一种方法Optional是使用感叹号:
Optional
println(todayTitle!)
但是,只有在确定存在该值的情况下,才应这样做。另一种方法是解包和使用条件,例如:
if let theTitle = todayTitle { println(theTitle) }
将该程序粘贴到runswiftlang中进行演示:
let todayTitle : String? = "today" println(todayTitle) println(todayTitle!) if let theTitle = todayTitle { println(theTitle) }