5

I have 4 text boxes.I don't want to allow user to let all these 4 textfields empty. How can I check multiple conditions in swift. I did like this but it's giving me an error

 if self.txtIncomeAd.text?.isEmpty && self.txtIncomeRec.text?.isEmpty &&

like wise. What is the correct way I can do this? Please help me. Thanks

user1960169
  • 3,533
  • 12
  • 39
  • 61

5 Answers5

5

you can simply use isEmpty property.

if !self.textFieldOne.text!.isEmpty && !self.textFieldTwo.text!.isEmpty && !self.textFieldThree.text!.isEmpty && !self.textFieldFour.text!.isEmpty {
 ...

}

or you can also safely unwrap the text value and the check that it is empty of not

if let text1 = self.textFieldOne.text, text2 = self.textFieldTwo.text, text3 = self.textFieldthree.text,text4 = self.textFieldFour.text where !text1.isEmpty && !text2.isEmpty && !text3.isEmpty && !text4.isEmpty {
  ...
  }

Or you can compare with Empty "" String

if self.textFieldOne.text != "" && self.textFieldTwo.text != "" && self.textFieldThree.text != "" && self.textFieldFour.text != ""   {
  ...
}

and we can also do this with Guard

guard let text = self.myTextField.text  where !text.isEmpty else {
  return
}
Sahil
  • 9,096
  • 3
  • 25
  • 29
1
if !self.txtIncomeAd.text!.isEmpty && !self.txtIncomeRec.text!.isEmpty && !self.txtIncomeAd.text!.isEmpty && !self.txtIncomeRec.text!.isEmpty
{
    ...
}
Jayesh Miruliya
  • 3,279
  • 2
  • 25
  • 22
0

It gives you an error because the text in the textField is optional. First you have to unwrap them all.

if let txtIncomeAd = self.txtIncomeAd.text,
     let txtIncomeRec = self.txtIncomeRec.text {
            if txtIncomeAd.isEmpty && txtIncomeRec.isEmpty {
                 // Do Something
            }
} else {
    // Empty text field
}
gasho
  • 1,926
  • 1
  • 16
  • 20
0

You can check with isEmpty boolean property.

 if ((inputTextField.text?.isEmpty) != nil && (inputTextField1.text?.isEmpty)!= nil && (inputTextField2.text?.isEmpty)!=nil) {

    }

or

  if ((inputTextField.text?.isEmpty)! && (inputTextField1.text?.isEmpty)! && (inputTextField2.text?.isEmpty)!) {

    }
Santo
  • 1,611
  • 3
  • 17
  • 37
0

Here's something a bit different:

extension UILabel {
    var textIsEmpty: Bool { return text?.isEmpty ?? true }
}

class MyClass: UIView {
    let txtIncomeAd = UILabel()
    let txtIncomeRec = UILabel()

    var textFieldsAreNonEmpty: Bool {
        return ![txtIncomeAd, txtIncomeRec].contains { $0.textIsEmpty }
    }
}

let c = MyClass()

c.txtIncomeAd.text = "hello"
c.txtIncomeRec.text = "there"

if c.textFieldsAreNonEmpty {
    print("text fields are valid")
}
par
  • 17,361
  • 4
  • 65
  • 80