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?
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.
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()) == "")
}
}
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 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) == "")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With