【问题标题】:Cast from 'Error' to unrelated type 'AuthErrorCode' always fails从“错误”转换为不相关类型“AuthErrorCode”总是失败
【发布时间】:2021-03-01 09:54:37
【问题描述】:

我尝试从 FirebaseAuth 获取错误代码并显示与错误代码相关的内容。我尝试用开关来做到这一点:

Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
            if let error = error as? AuthErrorCode {
                switch error {
                case .emailAlreadyInUse:
                    Utility.showAlertView(with: "Email already used", and: "Please choose a different email adress", in: self)
                case .invalidEmail:
                    Utility.showAlertView(with: "Email is invalid", and: "Please enter a valid email", in: self)
                case .weakPassword:
                    Utility.showAlertView(with: "Weak Password", and: "Please Choose a longer Password", in: self)
                default:
                    break
                }
            } else {
                

            }
        }

但我收到警告:

从 'Error' 转换为不相关的类型 'AuthErrorCode' 总是失败

我不知道该怎么办。 谢谢你的时间,Boothosh

【问题讨论】:

  • 你检查过这个stackoverflow.com/questions/45339861/… 吗?
  • 我已经检查过了,但我不明白我的代码有什么问题... :(
  • 什么是errror(有四个r)? ;-)
  • 是的,这是一个错误,但我在源代码中写的一切都很好

标签: swift firebase-authentication


【解决方案1】:

根据Firebase documentation AuthErrorCode 是 int enum,因此您不能将 Error 投射到其中。相反,您需要使用错误代码并尝试使用它创建AuthErrorCode 的实例:

    let code = (error as NSError).code
    if let code = AuthErrorCode(rawValue: code) {
        switch code {
        case .emailAlreadyInUse:
            Utility.showAlertView(with: "Email already used", and: "Please choose a different email adress", in: self)
        case .invalidEmail:
            Utility.showAlertView(with: "Email is invalid", and: "Please enter a valid email", in: self)
        case .weakPassword:
            Utility.showAlertView(with: "Weak Password", and: "Please Choose a longer Password", in: self)
        default:
            break
        }
    }

更新

对于可选错误,您需要在使用其代码之前对其进行解包:

if let err = error as NSError?, let code = AuthErrorCode(rawValue: err.code) {
   switch code {
      ...
   }
}

【讨论】:

  • 好的,我试过了,结果如下:我收到一个错误,上面写着“'错误?'不能转换为 'NSError';你的意思是使用 'as!'强迫沮丧?”感谢您的时间 Boothosh
  • @Boothosh 不,我不建议强制向下转换。我将针对可选错误更新我的答案
【解决方案2】:

AuthErrorCode 是一个以 Int 作为关联类型的枚举,因此您不能将错误变量直接转换为它。而是将错误转换为 NSError 并将 NSError 错误代码与枚举进行比较。

if let error = error as? NSError, errorCode = AuthErrorCode(rawValue: error.code) {
    switch errorCode {
        case .emailAlreadyInUse:
             //...
        case .errorCodeInvalidEmail:
             //...
        // more case
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多