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

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


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)}


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? = nilvar 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


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.2

Of course, replace "unavailable" with whatever suits you: "nil", "not found" etc