3
textField.text.isEmpty
textField.text != ""

These two functions regard spaces as characters. However, I would like my to recognise when the text field has no spaces or is not empty.

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 1
    You probably want to 'trim' whitespaces, just like in : http://stackoverflow.com/questions/26797739/does-swift-has-trim-method-on-string – Pieter21 May 30 '16 at 20:15
  • Trim removes spaces and line-breaks from beginning and end of string. That´s what you are looking for ? Take a look at: [Does swift has trim method on String?](http://stackoverflow.com/questions/26797739/does-swift-has-trim-method-on-string). – Tiago Luz May 30 '16 at 20:16
  • @Pieter21 That works fine, thanks! –  May 30 '16 at 20:21

3 Answers3

7

Just check if the trimmed string is empty

let isEmpty = str.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()).isEmpty

You can even put it in an String extension:

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

It even works for a string like var str = " ​ " (that has spaces, tabs and zero-width spaces).

Then simply check textField.text?.isReallyEmpty ?? true.

If you wanna go even further (I wouldn't) add it to an UITextField extension:

extension UITextField {
    var isReallyEmpty: Bool {
        return text?.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()).isEmpty ?? true
    }
}

Your code becomes textField.isReallyEmpty.

fpg1503
  • 7,492
  • 6
  • 29
  • 49
6

In Swift 4,

extension String {
    var isReallyEmpty: Bool {
        return self.trimmingCharacters(in: .whitespaces).isEmpty
    }
}
Angi
  • 67
  • 1
  • 4
0

I used this from @Pieter21 's link. It works for as many blank spaces a user could enter.

let myString = TextField.text

let trimmedString = myString!.stringByTrimmingCharactersInSet(
    NSCharacterSet.whitespaceAndNewlineCharacterSet()
)

if trimmedString != "" {
    // Code if not empty
} else {
    // Code if empty
}