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)
}
}
Another, slightly more compact, way (clearly debatable, but it's at least a single liner)
(result["ip"] ?? "unavailable").description
.In theory
result["ip"] ?? "unavailable"
should have work too, but it doesn't, unless in 2.2Of course, replace "unavailable" with whatever suits you: "nil", "not found" etc
Swift 3.1
From Swift 3, you can use
String(describing:)
to print out optional value. But the syntax is quite suck and the result isn't easy to see in console log.So that I create a extension of
Optional
to make a consistentnil
value.How to use:
Result:
I'm not sure what the proper process is for linking to other answers, but my answer to a similar question applies here as well.
Valentin's answer works well enough for optionals of type
String?
, but won't work if you want to do something like:One way to get rid of the
Optional
is to use an exclamation point: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:
Paste this program into runswiftlang for a demo:
With some try, I think this way is better.
Use
??
for default value and then use!
for unwrap optional variable.Here is example,
It will print
initialize
Printing
This will avoid word "optional" before the string.