Check string for nil & empty

后端 未结 23 1331
感动是毒
感动是毒 2020-12-07 10:53

Is there a way to check strings for nil and \"\" in Swift? In Rails, I can use blank() to check.

I currently have this, but i

23条回答
  •  再見小時候
    2020-12-07 11:11

    In my opinion, the best way to check the nil and empty string is to take the string count.

    var nilString : String?
    print(nilString.count) // count is nil
    
    var emptyString = ""
    print(emptyString.count) // count is 0
    
    // combine both conditions for optional string variable
    if string?.count == nil || string?.count == 0 {
       print("Your string is either empty or nil")
    }
    

提交回复
热议问题