6

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
    }
 }
3
  • see this may be it helps you stackoverflow.com/questions/29381994/check-string-for-nil-empty Commented May 31, 2018 at 13:25
  • if !(title?.isEmpty ?? true) { /* do you stuff */ } Commented May 31, 2018 at 19:06
  • there's something to be said for spelling it out in full: if title != nil && !title!.isEmpty Commented Nov 16, 2021 at 22:14

1 Answer 1

12

I would go with something like

if let title = object.title, !title.isEmpty {
  // it's not nil nor an empty string
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.