Check string for nil & empty

Is there a way to check strings for nil and "" in Swift? In Rails, I can use blank() to check.

I currently have this, but it seems overkill:

    if stringA? != nil {
        if !stringA!.isEmpty {
            ...blah blah
        }
    }

Solution 1:

If you're dealing with optional Strings, this works:

(string ?? "").isEmpty

The ?? nil coalescing operator returns the left side if it's non-nil, otherwise it returns the right side.

You can also use it like this to return a default value:

(string ?? "").isEmpty ? "Default" : string!

Solution 2:

You could perhaps use the if-let-where clause:

Swift 3:

if let string = string, !string.isEmpty {
    /* string is not blank */
}

Swift 2:

if let string = string where !string.isEmpty {
    /* string is not blank */
}