Search code examples
iosswiftswift3

Swift How to use single guard let statement for multiple UITextField


Hello All I am currently having issues tryin to use one guard let for a couple of textfield instaed of multiple guard let for each textfield and an UIAlertController if any textfield is empty. This is the code I tried below. But the alert controller is not being called. Can someone please advise me what am doing wrong

    @IBAction func submitBankInfo(_ textField: UITextField) {
       self.view.endEditing(true)
       guard let accountOwner = accountOwnerTxt.text, accountOwner !   
         = "", let accountNumber = accountNumberTxt.text, accountNumber !
       = "", let bvn = bvnTxt.text, bvn != "", let bankName = 
      nameOfBankTxt.text, bankName != "" else {
        if textField.text == nil {
            switch textField {
            case accountNumberTxt:
                OperationQueue.main.addOperation {
                    self.showAlert(title: "Error!", message: "Account is required.Please enter your number")
                }
            case bvnTxt:
                OperationQueue.main.addOperation {
                    self.showAlert(title: "Error!", message: "BVN is required.Please enter your bank verification number(BVN)")
                }
            case nameOfBankTxt:
                OperationQueue.main.addOperation {
                    self.showAlert(title: "Error!", message: "Bank name     required.Please enter your bank name")
                }
            default:
                break
            }
        }

        return
    }

Solution

  • You could use an embedded function to generalize the validation and keep your guard statement focused on the valid scenario.

    @IBAction func submitBankInfo(_ textField: UITextField) 
    {
       self.view.endEditing(true)
    
       func validField(_ field:UITextField, _ message:String) -> String?
       { 
          if let fieldValue = field.text, fieldValue != ""
          { return fieldValue }
          OperationQueue.main.addOperation 
          { self.showAlert(title: "Error!", message: message) }
          return nil 
       }
    
       guard let accountOwner  = validField(accountOwnerTxt, "Account owner is required.Please enter your identification"),
             let accountNumber = validField(accountNumberTxt,"Account is required.Please enter your number"),
             let bvn           = validField(bvnTxt,          "BVN is required.Please enter your bank verification number(BVN)"),
             let bankName      = validField(nameOfBankTxt,   "Bank name required.Please enter your bank name")
       else  { return }
    
       // proceed with valid data ...
    }