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

Swifter way to check optional and then type

在 Swift3 中我有这样的代码

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

当然这是废话,而且经常崩溃。

1) 整个事情可以是零

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

这非常可靠

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 = ""
}

(除非我忘记了什么。)

但它看起来很不迅速和冗长。有没有更好的办法?如果不是更好,更短?

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