Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift4 how to check if string is not nil and not empty? [duplicate]

Tags:

string

ios

swift4

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
    }
 }
like image 734
Alex Stone Avatar asked Jan 28 '23 00:01

Alex Stone


1 Answers

I would go with something like

if let title = object.title, !title.isEmpty {
  // it's not nil nor an empty string
}
like image 171
pstued Avatar answered Feb 07 '23 18:02

pstued