gpt4 book ai didi

ios - Swift:正确处理登录错误状态?

转载 作者:行者123 更新时间:2023-11-29 02:07:57 25 4
gpt4 key购买 nike

我一直在努力寻找一种更好的方法来处理我的错误状态。

目前我有大约 10 个 if else 语句,这显然是处理错误的低效方法。

从我能够找到的内容来看,枚举似乎是可行的方法。但是我一直没能成功实现它。

我能找到的每个例子都遵循这种形式:

enum Result<T> {
case Success(T)
case Failure(String)
}

var result = divide(2.5, by:3)

switch result {
case Success(let quotient):
doSomethingWithResult(quotient)
case Failure(let errString):
println(errString)
}

但我不太明白这对我的错误状态有何影响。

没有 if 语句,更不用说解释在哪里实现这些语句,而且它们都只有 1 个“action”,在上面的示例中是一个 println。

我需要为每个错误状态运行几行代码。

这是我对电子邮件文本字段的错误处理示例。

    if textField == emailTextField {
emailTextField.textColor = UIColor.formulaBlackColor()
emailIcon.setTitleColor(UIColor.formulaBlackColor(), forState: .Normal)
emailTextField.resignFirstResponder()
if textField.text.isEmpty {
emailIcon.setTitleColor(UIColor.formulaRedColor(), forState: .Normal)
emailState.text = ""
emailTextField.attributedPlaceholder = NSAttributedString(string:"Email Address",
attributes:[NSForegroundColorAttributeName: UIColor.formulaRedColor()])
showError("Please enter your email.")
} else if emailTextField.text.isValidEmail() == false {
emailIcon.setTitleColor(UIColor.formulaRedColor(), forState: .Normal)
emailTextField.textColor = UIColor.formulaRedColor()
emailState.text = ""
showError("Please enter a valid email address")
} else {
emailIcon.setTitleColor(UIColor.formulaBlackColor(), forState: .Normal)
emailState.textColor = UIColor.formulaGreenColor()
emailState.text = ""
hideError()
}
}

我一直在尝试创建这样的枚举:

enum Login {
case NoInternetConnection
case NoEmail
case InvalidEmail
case NoPassword
case WrongEmailOrPassword
case Success
}

但我还没有找到一种方法来完成这项工作。

当我添加 switch case 时,出现错误“预期声明”,

我尝试将其放入函数中,错误消失了。但我一直不知道如何处理这些案例。

switch Login {
case Success:println("CASE SUCCESS")
case NoEmail:println("CASE NoEmail")
}

显然我仍然需要以某种方式实现我的 if 语句来检查例如如果 emailTextField 为空?但是我怎样才能将案例设置为 NoEmail。并让它运行几行代码?

最佳答案

您首先需要拥有该枚举的值,您可以检查它,如下所示:

enum Login {
case NoInternetConnection
case NoEmail
case InvalidEmail
case NoPassword
case WrongEmailOrPassword
case Success
}

// Here you get your result, e.g. from a function.
let loginResult = Login.Success

switch loginResult {
case let .NoInternetConnection:
println("No internet connection")
case let .NoEmail:
println("No email specified")
case let .InvalidEmail:
println("Email invalid")
case let .NoPassword:
println("No password specified")
case let .WrongEmailOrPassword:
println("Email or password wrong")
case let .Success:
println("Success")
}

请记住还有另一种方法,即 Optional Chaining .

在我看来,最好将此类条件链分解为多个函数(另请参阅 Clean Code),但不幸的是 Swift 不支持捕获异常,因此我们必须采用这种方式。

关于ios - Swift:正确处理登录错误状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29591531/

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