iOS Swift4如何检查字符串是否为空且不为空?

时间:2018-05-31 13:23:23

标签: ios string swift4

如何检查可选字符串对象是否都是空字符串""在Swift4中也没有?我最终不得不写这些奇怪的检查,因为

 //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
    }
 }

1 个答案:

答案 0 :(得分:4)

我会选择像

这样的东西
if let title = object.title, !title.isEmpty {
  // it's not nil nor an empty string
}