Check empty string in Swift?

前端 未结 15 1846
臣服心动
臣服心动 2020-11-28 03:51

In Objective C, one could do the following to check for strings:

if ([myString isEqualToString:@\"\"]) {
    NSLog(@\"m         


        
相关标签:
15条回答
  • 2020-11-28 04:13

    In Xcode 11.3 swift 5.2 and later

    Use

    var isEmpty: Bool { get } 
    

    Example

    let lang = "Swift 5"
    
    if lang.isEmpty {
       print("Empty string")
    }
    

    If you want to ignore white spaces

    if lang.trimmingCharacters(in: .whitespaces).isEmpty {
       print("Empty string")
    }
    
    0 讨论(0)
  • 2020-11-28 04:13

    To do the nil check and length simultaneously Swift 2.0 and iOS 9 onwards you could use

    if(yourString?.characters.count > 0){}
    
    0 讨论(0)
  • 2020-11-28 04:14

    For optional Strings how about:

    if let string = string where !string.isEmpty
    {
        print(string)
    }
    
    0 讨论(0)
  • 2020-11-28 04:17

    A concise way to check if the string is nil or empty would be:

    var myString: String? = nil
    
    if (myString ?? "").isEmpty {
        print("String is nil or empty")
    }
    
    0 讨论(0)
  • 2020-11-28 04:19

    I am completely rewriting my answer (again). This time it is because I have become a fan of the guard statement and early return. It makes for much cleaner code.

    Non-Optional String

    Check for zero length.

    let myString: String = ""
    
    if myString.isEmpty {
        print("String is empty.")
        return // or break, continue, throw
    }
    
    // myString is not empty (if this point is reached)
    print(myString)
    

    If the if statement passes, then you can safely use the string knowing that it isn't empty. If it is empty then the function will return early and nothing after it matters.

    Optional String

    Check for nil or zero length.

    let myOptionalString: String? = nil
    
    guard let myString = myOptionalString, !myString.isEmpty else {
        print("String is nil or empty.")
        return // or break, continue, throw
    }
    
    // myString is neither nil nor empty (if this point is reached)
    print(myString)
    

    This unwraps the optional and checks that it isn't empty at the same time. After passing the guard statement, you can safely use your unwrapped nonempty string.

    0 讨论(0)
  • 2020-11-28 04:19

    Check check for only spaces and newlines characters in text

    extension String
    {
        var  isBlank:Bool {
            return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
        }
    }
    

    using

    if text.isBlank
    {
      //text is blank do smth
    }
    
    0 讨论(0)
提交回复
热议问题