1

I have some multiple textfields, And If all the fields are filled then only I have to call some method else I have to throw alert.

But, even textfields are empty, It is executing condition as false.

if genderTextField.text?.isEmpty == true && weightTextField.text?.isEmpty == true && heightTextField.text?.isEmpty == true {
                self.showAlert(withTitle:"Title", withMessage: "Fill all the fields")

} else {
 //call some function
}

But, If I print textfields text

po genderTextField.text
▿ Optional<String>
  - some : ""

Any suggestions?

2
  • 2
    You should use OR, if you want to check if all the TextFields are filled Commented May 12, 2020 at 10:29
  • 2
    Your logic is wrong for a start. - you want || (or) not and - you want the alert if any field is empty. You can also omit the == true since isEmpty is a Boolean. I would suggest that you handle nil properly via a nil coalescing operator if (genderTextField.text ?? "").isEmpty ... Commented May 12, 2020 at 10:33

1 Answer 1

2

Swift 5.2

A more elegant way to do it would be to create an extension on UITextField

extension UITextField {
    var isEmpty: Bool {
        if let text = self.text, !text.isEmpty {
            return false
        } else {
            return true
        }
    }
}

And then you check like this:

if genderTextField.isEmpty || weightTextField.isEmpty || heightTextField.isEmpty {
    showAlert()
} else {
    // do something else
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.