更快捷的方式检查可选,然后键入

时间:2016-12-20 20:04:52

标签: types swift3 optional

在Swift3中我有像这样的代码

var result: String = ""
...
result = try db?.scalar(q) as! String

当然是那种废话,经常崩溃。

1)整件事可以是零

2)因为它是一个可选的绑定,它可能不是一个String

这非常可靠

if let sc = try db?.scalar(q) {
    print("good news, that is not nil!")
    if sc is String {
        print("good news, it is a String!")
        result = sc as! String
    } else {
        print("bizarrely, it was not a String. but at least we didn't crash")
        result = ""
    }
else {
    print ("the whole thing is NIL!  wth.")
    result = ""
}

(除非我忘记了什么。)

但它似乎非常无益且冗长。有没有更好的办法?如果不是更好,更短?

1 个答案:

答案 0 :(得分:1)

if let sc = try db?.scalar(q) as? String { ...
    print("good news, that is not nil!")
    print("good news, it is a String!")
    result = sc
else {
    print("bizarrely, it was not a String. but at least we didn't crash")
    result = ""
}

如果你想要得到的只是String值(如果是非零,并且正确输入为String)或"",那么就这样做:

let result = try db?.scalar(q) as? String ?? ""