82

This is an extension, not a duplicate, of How to check if a text field is empty or not in swift

The given answer,

@IBAction func Button(sender: AnyObject) {
    if textField1.text != ""  {
        // textfield 1 
    }
}

does not work for me, i.e., the if-loop is triggered even when nothing is entered in the text field. (I have modified it from the original because I'm looking to trigger the code only when the field contains text).

The second answer

@IBAction func Button(sender: AnyObject) {
    if !textField1.text.isEmpty{

    }
}

comes much closer, but it accepts strings like " " as not empty. I could build something myself, but is there a function that will check if a string contains something other than whitespace?

Community
  • 1
  • 1
thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
  • 1
    Here is the same question with solutions in Objective-C: http://stackoverflow.com/questions/8238691/how-to-know-if-a-uitextfield-in-ios-has-blank-spaces. It should be easy to translate that to Swift. – Martin R Jan 04 '15 at 17:12

12 Answers12

189

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.

akashivskyy
  • 44,342
  • 16
  • 106
  • 116
  • 5
    Might I suggest `!str.stringByTrimmingCharactersInSet(whitespaceSet).isEmpty`? I _think_ `isEmpty` might be a little quicker since it's O(N). – Ryan Feb 24 '16 at 18:40
  • 3
    I'd say isEmpty is or at least should be O(1) :) – Przemysław Wrzesiński Nov 04 '16 at 11:26
  • how to check the docs here lets say, inside the parenthesis (in: .whitespaces). What are the other options besides whitespaces? and when is trimmingCharacters only available? Im learning how to use docs but I cant seem to find them unless i search them on Stackoverflow. Please advise. thanks – Gel Feb 22 '19 at 20:27
  • 1
    @GelSisaed The documentation of `CharacterSet` along with all predefined values can be found here: https://developer.apple.com/documentation/foundation/characterset – akashivskyy Feb 25 '19 at 11:37
25

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()) == "")
    }
}
Taylor M
  • 1,855
  • 1
  • 14
  • 20
Doolali
  • 956
  • 9
  • 13
  • I'm getting `Value of type 'String' has no member 'stringByTrimmingCharactersInSet'` so it doesn't work or it's imcomplete – Arturo Apr 23 '22 at 20:06
12

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) == "")
    }
}
Community
  • 1
  • 1
Mark Moeykens
  • 15,915
  • 6
  • 63
  • 62
5

akashivskyy answer in Swift 3.0:

let whitespaceSet = CharacterSet.whitespaces
if !str.trimmingCharacters(in: whitespaceSet).isEmpty {
  // string contains non-whitespace characters
}
ronatory
  • 7,156
  • 4
  • 29
  • 49
4
extension StringProtocol where Index == String.Index {
    var isEmptyField: Bool {
        return trimmingCharacters(in: .whitespaces) == ""
    }
}


if yourTextField.text.isEmptyField {
    // Field is empty
} else {
    // Field is NOT empty
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
4

Answer in swift 4:

extension String {
    func isEmptyOrWhitespace() -> Bool {
        if(self.isEmpty) {
            return true
        }
        return (self.trimmingCharacters(in: NSCharacterSet.whitespaces) == "")
    }
}
Dylan
  • 111
  • 6
3

Answer in Swift 3.0

if stringValue.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty
{}
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
2

Answer in Swift 3.*, considers newlines, tabs

extension String {

    var containsNonWhitespace: Bool {
        return !self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }

}
Ilia Khalyapin
  • 148
  • 1
  • 7
KimJ
  • 29
  • 3
  • This question already has an accepted answer, along with another up-voted answer in Swift 3. –  May 02 '17 at 16:50
1

Answer with a picture in case you need a demo

// MY FUNCTIONS
private func checkMandatoryFields(){

    //CHECK EMPTY OR SPACES ONLY FIELDS
    if let type = typeOutle.text, let name = nameOutlet.text, let address = addressOutlet.text, type.trimmingCharacters(in: .whitespaces).isEmpty || name.trimmingCharacters(in: .whitespaces).isEmpty || address.trimmingCharacters(in: .whitespaces).isEmpty {
        print("Mandatory fields are: ")
        errorDisplay(error: "Mandatory fields are: Type, Name, Address.")
        return
    }

}

enter image description here

coders
  • 2,287
  • 1
  • 12
  • 20
1

Method

 func trim() -> String {
    return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
}

Use

if textField.text.trim().count == 0 {
    // Do your stuff
}
0

swift 4.2

@IBAction func checkSendButton(_ sender: UITextField) {
    if((sender.text?.count)! > 0 && !(sender.text!.trimmingCharacters(in: .whitespaces)).isEmpty){
        self.sendButton.isEnabled = true
    }
    else{
        self.sendButton.isEnabled = false
    }
}
Ahmed Safadi
  • 4,402
  • 37
  • 33
0

In Swift 5.7.2 (but probably earlier) CharacterSet conforms to SetAlgebra.

So instead of creating a copy of the string with trimmingCharacters(in:) and .whitespacesAndNewlines it is possible to create a CharacterSet from the string using init(charactersIn:) and check that it is not a subset of .whitespacesAndNewlines

For example :

extension String {
    func hasOnlyCharachersIn(_ characterSet: CharacterSet) -> Bool {
        let charactersInSelf = CharacterSet(charactersIn: self)
        return charactersInSelf.isSubset(of: characterSet)
    }
    
    var hasNonWhitespaceCharacters: Bool {
        !hasOnlyCharachersIn(.whitespacesAndNewlines)
    }
}

produces in a playground:

var testString = ""
testString.hasNonWhitespaceCharacters // false

testString = " "
testString.hasNonWhitespaceCharacters // false

testString = "\t"
testString.hasNonWhitespaceCharacters // false

testString = " \t\n"
testString.hasNonWhitespaceCharacters // false

testString = "\n"
testString.hasNonWhitespaceCharacters // false

testString = "foo"
testString.hasNonWhitespaceCharacters // true

testString = "foo bar"
testString.hasNonWhitespaceCharacters // true

testString = "foo\tbar"
testString.hasNonWhitespaceCharacters // true

testString = "foo bar\tbaz\n"
testString.hasNonWhitespaceCharacters // true
AnderCover
  • 2,488
  • 3
  • 23
  • 42