Check string for nil & empty

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

    If you're dealing with optional Strings, this works:

    (string ?? "").isEmpty
    

    The ?? nil coalescing operator returns the left side if it's non-nil, otherwise it returns the right side.

    You can also use it like this to return a default value:

    (string ?? "").isEmpty ? "Default" : string!
    
    0 讨论(0)
  • 2020-12-07 11:27

    Swift 3 This works well to check if the string is really empty. Because isEmpty returns true when there's a whitespace.

    extension String {
        func isEmptyAndContainsNoWhitespace() -> Bool {
            guard self.isEmpty, self.trimmingCharacters(in: .whitespaces).isEmpty
                else {
                   return false
            }
            return true
        }
    }
    

    Examples:

    let myString = "My String"
    myString.isEmptyAndContainsNoWhitespace() // returns false
    
    let myString = ""
    myString.isEmptyAndContainsNoWhitespace() // returns true
    
    let myString = " "
    myString.isEmptyAndContainsNoWhitespace() // returns false
    
    0 讨论(0)
  • 2020-12-07 11:28

    Swift 3 For check Empty String best way

    if !string.isEmpty{
    
    // do stuff
    
    }
    
    0 讨论(0)
  • 2020-12-07 11:30

    You could perhaps use the if-let-where clause:

    Swift 3:

    if let string = string, !string.isEmpty {
        /* string is not blank */
    }
    

    Swift 2:

    if let string = string where !string.isEmpty {
        /* string is not blank */
    }
    
    0 讨论(0)
  • 2020-12-07 11:31

    You should do something like this:
    if !(string?.isEmpty ?? true) { //Not nil nor empty }

    Nil coalescing operator checks if the optional is not nil, in case it is not nil it then checks its property, in this case isEmpty. Because this optional can be nil you provide a default value which will be used when your optional is nil.

    0 讨论(0)
提交回复
热议问题