Is there a way to check strings for nil
and \"\"
in Swift? In Rails, I can use blank()
to check.
I currently have this, but i
I know there are a lot of answers to this question, but none of them seems to be as convenient as this (in my opinion) to validate UITextField
data, which is one of the most common cases for using it:
extension Optional where Wrapped == String {
var isNilOrEmpty: Bool {
return self?.trimmingCharacters(in: .whitespaces).isEmpty ?? true
}
}
You can just use
textField.text.isNilOrEmpty
You can also skip the .trimmingCharacters(in:.whitespaces)
if you don't consider whitespaces as an empty string or use it for more complex input tests like
var isValidInput: Bool {
return !isNilOrEmpty && self!.trimmingCharacters(in: .whitespaces).characters.count >= MIN_CHARS
}