How do I check if an optional string object is neither empty string "" nor nil in Swift4? I end up having to write weird checks like these, because
//object has instance variable
var title: String?
//invalid comparison - cannot compare optional and non optional
if object.title?.count > 0
{
}
//valid but ugly
if object.titleString == nil {
//has nil title
}
if let title = object.title
{
if title.count == 0
{
//has a "" string
}
}
I would go with something like
if let title = object.title, !title.isEmpty {
// it's not nil nor an empty string
}
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