Check if Swift text field contains non-whitespace

Below is the extension I wrote that works nicely, especially for those that come from a .NET background:

extension String {
    func isEmptyOrWhitespace() -> Bool {

        if(self.isEmpty) {
            return true
        }

        return (self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "")
    }
}

This answer was last revised for Swift 5.2 and iOS 13.5 SDK.


You can trim whitespace characters from your string and check if it's empty:

if !textField1.text.trimmingCharacters(in: .whitespaces).isEmpty {
    // string contains non-whitespace characters
}

You can also use .whitespacesAndNewlines to remove newline characters too.


Swift 4.2

Extension for String is empty or whitespace

extension String {
    func isEmptyOrWhitespace() -> Bool {
        
        // Check empty string
        if self.isEmpty {
            return true
        }
        // Trim and check empty string
        return (self.trimmingCharacters(in: .whitespaces) == "")
    }
}

The original poster's code is checking text on a textfield which is optional. So he will need some code to check optional strings. So let's create a function to handle that too:

Extension for Optional String is nil, empty or whitespace

extension Optional where Wrapped == String {
    func isEmptyOrWhitespace() -> Bool {
        // Check nil
        guard let this = self else { return true }
        
        // Check empty string
        if this.isEmpty {
            return true
        }
        // Trim and check empty string
        return (this.trimmingCharacters(in: .whitespaces) == "")
    }
}

akashivskyy answer in Swift 3.0:

let whitespaceSet = CharacterSet.whitespaces
if !str.trimmingCharacters(in: whitespaceSet).isEmpty {
  // string contains non-whitespace characters
}

Tags:

Swift