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.
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"
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With