How to print a string from plist without “Optional”?

北慕城南 提交于 2019-11-28 09:46:56

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

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

Jeremy

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

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

initialize

Var text: string? = nil

Printing

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

This will avoid word "optional" before the string.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!