Check string for nil & empty

后端 未结 23 1339
感动是毒
感动是毒 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:08

    Using isEmpty

    "Hello".isEmpty  // false
    "".isEmpty       // true
    

    Using allSatisfy

    extension String {
      var isBlank: Bool {
        return allSatisfy({ $0.isWhitespace })
      }
    }
    
    "Hello".isBlank        // false
    "".isBlank             // true
    

    Using optional String

    extension Optional where Wrapped == String {
      var isBlank: Bool {
        return self?.isBlank ?? true
      }
    }
    
    var title: String? = nil
    title.isBlank            // true
    title = ""               
    title.isBlank            // true
    

    Reference : https://useyourloaf.com/blog/empty-strings-in-swift/

提交回复
热议问题