Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

swift - How to print a string from plist without "Optional"?

I load a value from a dictionary in a plist but when I print it to the console, it prints: Optional(Monday Title) rather than just "Monday Title".

How can I get rid of the Optional() of my value when printing?

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)
        }
    }    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to get rid of the Optional is to use an exclamation point:

println(todayTitle!)

However, you should do it only if you are certain that the value is there. Another way is to unwrap and use a conditional, like this:

if let theTitle = todayTitle {
    println(theTitle)
}

Paste this program into runswiftlang for a demo:

let todayTitle : String? = "today"
println(todayTitle)
println(todayTitle!)
if let theTitle = todayTitle {
    println(theTitle)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...