Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check empty string in Swift?

Tags:

swift

People also ask

How do I check if a string is empty in Swift?

To check if string is empty in Swift, use the String property String. isEmpty . isEmpty property is a boolean value that is True if there are no any character in the String, or False if there is at least one character in the String.

How check string is value or not in Swift?

In Swift, you can check for string and character equality with the "equal to" operator ( == ) and "not equal to" operator ( != ).

How do I create an empty string in Swift?

To create an empty String value as the starting point for building a longer string, either assign an empty string literal to a variable, or initialize a new String instance with initializer syntax: var emptyString = "" // empty string literal.


There is now the built in ability to detect empty string with .isEmpty:

if emptyString.isEmpty {
    print("Nothing to see here")
}

Apple Pre-release documentation: "Strings and Characters".


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")
}

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.


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")
}

Here is how I check if string is blank. By 'blank' I mean a string that is either empty or contains only space/newline characters.

struct MyString {
  static func blank(text: String) -> Bool {
    let trimmed = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    return trimmed.isEmpty
  }
}

How to use:

MyString.blank(" ") // true

You can also use an optional extension so you don't have to worry about unwrapping or using == true:

extension String {
    var isBlank: Bool {
        return self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }
}
extension Optional where Wrapped == String {
    var isBlank: Bool {
        if let unwrapped = self {
            return unwrapped.isBlank
        } else {
            return true
        }
    }
}

Note: when calling this on an optional, make sure not to use ? or else it will still require unwrapping.