Swift如何为多个UITextField使用单保护let语句

时间:2017-04-11 14:36:58

标签: ios swift swift3

Hello All我目前遇到的问题是尝试使用一个警卫让一对文本字段实现多个警卫让每个文本字段和一个UIAlertController如果任何文本字段为空。这是我在下面尝试的代码。但是没有调用警报控制器。有人可以告诉我我做错了什么

    @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
    }

1 个答案:

答案 0 :(得分:3)

您可以使用嵌入式函数来概括验证,并将您的警卫声明集中在有效场景上。

@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 ...
}