20

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)
        }
    }    
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Rob Puryear
  • 411
  • 1
  • 3
  • 10

6 Answers6

39

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)
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Awesome! Thanks so much for the quick answer. I'm still getting used to these optionals. – Rob Puryear Oct 28 '14 at 03:25
  • @vacawama Thanks for alerting me to it! It looks like runswiftlang stopped supporting online demos, so I copied re-typed the code and pasted it here with instructions on how to try int online. I also removed the question mark. Thank you! – Sergey Kalinichenko Oct 28 '14 at 03:30
5

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
Johnny
  • 1,824
  • 23
  • 16
4

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

Rad'Val
  • 8,895
  • 9
  • 62
  • 92
  • 1
    Clever! As noted by @Jeremy, your default value should be of the same type as your optional. So, if you wanted to print an optional Int: `var i:Int?; print("i is: \((i ?? 0).description)") // output: "i is 0"` – Jason Moore Oct 26 '16 at 13:37
1

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 consistent nil value.

extension Optional {
    var logable: Any {
        switch self {
        case .none:
            return "⁉️" // Change you whatever you want
        case let .some(value):
            return value
        }
    }
}

How to use:

var a, b: Int?
a = nil
b = 1000
print("a: ", a.logable)
print("b: ", b.logable)

Result:

a: ⁉️
b: 1000
Community
  • 1
  • 1
nahung89
  • 7,745
  • 3
  • 38
  • 40
0

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:

let i? = 88
print("The value of i is: \(i ?? "nil")")  // Compiler error
Community
  • 1
  • 1
Jeremy
  • 934
  • 1
  • 10
  • 19
-1

initialize

Var text: string? = nil

Printing

print("my string", text! as string)

This will avoid word "optional" before the string.

Anish
  • 1