【问题标题】:Swift How to use single guard let statement for multiple UITextFieldSwift 如何对多个 UITextField 使用单个保护 let 语句
【发布时间】:2018-04-12 19:18:24
【问题描述】:

大家好,我目前在尝试使用一个保护让几个文本字段而不是多个保护让每个文本字段和一个 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
    }

【问题讨论】:

  • 定义“不工作”(请不要使用该术语。要清晰、简洁和具体)。 Edit你的问题说清楚。
  • @codeperfect 日志中的错误是什么??
  • != 用换行符分隔看起来很奇怪。有一个更简单的语法:!accountOwner.isEmpty
  • @maddy,我已经编辑了这个问题。谢谢
  • @vadian,真的没有错误。当 texfield 为空时,不会调用 alertcontroller

标签: ios swift swift3


【解决方案1】:

您可以使用嵌入式函数来概括验证,并使您的保护语句专注于有效场景。

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

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 1970-01-01
    • 2021-04-02
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    相关资源
    最近更新 更多