Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

plist

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)
        }
    }    
like image 955
Rob Puryear Avatar asked Oct 28 '14 03:10

Rob Puryear


2 Answers

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)
}
like image 88
Sergey Kalinichenko Avatar answered Oct 12 '22 13:10

Sergey Kalinichenko


With some try, I think this way is better.

(variableName ?? "default value")!

Use ?? for default value and then use ! for unwrap optional variable.

Here is example,

var a:String? = nil
var b:String? = "Hello"

print("varA = \( (a ?? "variable A is nil.")! )")
print("varB = \( (b ?? "variable B is nil.")! )")

It will print

varA = variable A is nil.
varB = Hello
like image 43
Johnny Avatar answered Oct 12 '22 12:10

Johnny