Fattie
Fattie

Reputation: 12206

Swifter way to check optional and then type

in Swift3 I had code like this

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

of course that's crap and often crashes.

1) the whole thing can be nil

2) since it's an optional binding, it may not be a String

This works pretty reliably

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

(Unless I forgot something.)

But it seems very nonswifty and long. Is there a better way? If not better, shorter?

Upvotes: 1

Views: 49

Answers (1)

Alexander
Alexander

Reputation: 63399

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

If all you're trying to get is the String value (if non-nil, and correctly types as String) or "", just do:

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

Upvotes: 1

Related Questions