Check string for nil & empty

后端 未结 23 1320
感动是毒
感动是毒 2020-12-07 10:53

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

23条回答
  •  無奈伤痛
    2020-12-07 11:21

    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
    }
    

提交回复
热议问题