gpt4 book ai didi

ios - Swift 如何对多个 UITextField 使用单个 guard let 语句

转载 作者:行者123 更新时间:2023-11-28 10:56:14 24 4
gpt4 key购买 nike

你好我目前有问题尝试使用一个 guard let 来处理几个文本字段而不是多个 guard let 用于每个文本字段和一个 UIAlertController(如果任何文本字段为空)。这是我在下面尝试的代码。但是没有调用警报 Controller 。有人可以告诉我做错了什么

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

最佳答案

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

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

关于ios - Swift 如何对多个 UITextField 使用单个 guard let 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com