枚举返回对象(NSError)

时间:2015-03-09 22:16:02

标签: swift enums

这个相对直截了当的enum,编译得很好,但是......

public protocol AuthKitErrorProtocol {
    var error: NSError { get }
}

enum AuthKitError: AuthKitErrorProtocol {
    case SignInFailedInvalidUsernamePassword
    case SignInFailedInvalidSecondFactor

    var error: NSError {
        let (codeK: Int,
        userInfoK: Dictionary<String, String>
        ) = {
            switch self {
            case .SignInFailedInvalidUsernamePassword:
                return (1000,
                    [ NSLocalizedDescriptionKey: "Operation failed.",
                        NSLocalizedFailureReasonErrorKey: "Invalid usename or password",
                        NSLocalizedRecoverySuggestionErrorKey: "Please try again" ]
                )

            case .SignInFailedInvalidSecondFactor:
                return (1001,
                    [ NSLocalizedDescriptionKey: "Operation failed.",
                        NSLocalizedFailureReasonErrorKey: "Invalid second factor code",
                        NSLocalizedRecoverySuggestionErrorKey: "Please try again" ]
                )

            default:
                return (-999,
                    [ NSLocalizedDescriptionKey: "Operation failed.",
                        NSLocalizedFailureReasonErrorKey: "Unknown reason",
                        NSLocalizedRecoverySuggestionErrorKey: "Please call customer support" ]
                )

            }
            }()

            return NSError(domain: kAuthKitErrorDomain, code: codeK, userInfo: userInfoK)
    }
}

但是当试图从中提取时

var err: NSError  = AuthKitError.SignInFailedInvalidUsernamePassword
println("error is : \(err)")

它失败了,说:

AuthKitError is not convertible to NSError

任何想法都将不胜感激!谢谢你的时间。

1 个答案:

答案 0 :(得分:1)

error是枚举的实例属性,AuthKitError.SignInFailedInvalidUsernamePassword是枚举的实例,因此您必须明确读取其值:

var err: NSError  = AuthKitError.SignInFailedInvalidUsernamePassword.error
                                                                    ^^^^^^