Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coalescing Swift operator for an empty non-nil string

I have a string variable in Swift:

let foo = "bar"

But it can also be any other arbitrary string. Now I want to do the following:

let bar = ... // either the value of foo, or if foo is "", it will be "default"

I looked up "coalescing operator" and it seems it's the right direction. I tried it with the following code:

let bar = foo ?? "default"

But it seems that when foo is empty, it will still take this, and it won't set default as the value.

I assume that coalescing operators only work with a nil value and not with empty strings. However, is there a solution where I can test my value for being an empty string, and assigning a default value? I can't use if/else, because it will be located in a class.

like image 666
Camillo Avatar asked Feb 04 '15 23:02

Camillo


2 Answers

Or create your own operator:

infix operator ??? {}
func ??? (lhs: String, rhs: String) -> String {
    if lhs.isEmpty {
        return rhs
    }
    return lhs
}

And then: let bar = foo ??? "default"

like image 163
return true Avatar answered Nov 15 '22 08:11

return true


There's a difference between "" and nil. As is, you are defining foo as "bar", and thus it is non optional so it will never return nil. It sounds like what you need is the ternary operator:

let bar = foo.isEmpty ? foo : "default"

Also, to expand on return true's answer, you could make an operator that accounts for both optional and empty strings like so:

infix operator ???? {}
func ???? (lhs: String?, rhs: String) -> String {
    if let s = lhs {
        if !s.isEmpty {
            return s
        }
    }    
    return rhs
}
like image 32
Ian Avatar answered Nov 15 '22 08:11

Ian