如何在没有“可选”的情况下从plist打印字符串?

时间:2022-08-01 21:42:46

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

我从plist中的字典加载一个值但是当我将它打印到控制台时,它会打印:可选(星期一标题)而不仅仅是“星期一标题”。

How can I get rid of the Optional() of my value when printing?

如何在打印时摆脱我的值的Optional()?

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

6 个解决方案

#1


36  

One way to get rid of the Optional is to use an exclamation point:

摆脱Optional的一种方法是使用感叹号:

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:

将此程序粘贴到runswiftlang中进行演示:

let todayTitle : String? = "today"
println(todayTitle)
println(todayTitle!)
if let theTitle = todayTitle {
    println(theTitle)
}

#2


4  

Another, slightly more compact, way (clearly debatable, but it's at least a single liner)

另一种稍微紧凑的方式(显然有争议,但它至少是一个单一的衬垫)

(result["ip"] ?? "unavailable").description.

(结果[“ip”] ??“不可用”)。描述。

In theory result["ip"] ?? "unavailable" should have work too, but it doesn't, unless in 2.2

理论上结果[“ip”] ?? “不可用”也应该有效,但事实并非如此,除非在2.2中

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

当然,用适合你的东西替换“不可用”:“nil”,“not found”等

#3


3  

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

#4


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:

Valentin的答案适用于String类型的选项,但如果您想要执行以下操作,则无效:

let i? = 88
print("The value of i is: \(i ?? "nil")")  // Compiler error

#5


0  

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.

从Swift 3中,您可以使用String(描述:)打印出可选值。但语法很糟糕,结果在控制台日志中不容易看到。

So that I create a extension of Optional to make a consistent nil value.

因此,我创建了一个Optional的扩展来生成一致的nil值。

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

#6


-1  

initialize

初始化

Var text: string? = nil

Printing

印花

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

This will avoid word "optional" before the string.

这将避免字符串前的“可选”字样。

#1


36  

One way to get rid of the Optional is to use an exclamation point:

摆脱Optional的一种方法是使用感叹号:

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:

将此程序粘贴到runswiftlang中进行演示:

let todayTitle : String? = "today"
println(todayTitle)
println(todayTitle!)
if let theTitle = todayTitle {
    println(theTitle)
}

#2


4  

Another, slightly more compact, way (clearly debatable, but it's at least a single liner)

另一种稍微紧凑的方式(显然有争议,但它至少是一个单一的衬垫)

(result["ip"] ?? "unavailable").description.

(结果[“ip”] ??“不可用”)。描述。

In theory result["ip"] ?? "unavailable" should have work too, but it doesn't, unless in 2.2

理论上结果[“ip”] ?? “不可用”也应该有效,但事实并非如此,除非在2.2中

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

当然,用适合你的东西替换“不可用”:“nil”,“not found”等

#3


3  

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

#4


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:

Valentin的答案适用于String类型的选项,但如果您想要执行以下操作,则无效:

let i? = 88
print("The value of i is: \(i ?? "nil")")  // Compiler error

#5


0  

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.

从Swift 3中,您可以使用String(描述:)打印出可选值。但语法很糟糕,结果在控制台日志中不容易看到。

So that I create a extension of Optional to make a consistent nil value.

因此,我创建了一个Optional的扩展来生成一致的nil值。

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

#6


-1  

initialize

初始化

Var text: string? = nil

Printing

印花

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

This will avoid word "optional" before the string.

这将避免字符串前的“可选”字样。