Swift枚举作为函数中的参数

帕尔默

我有一个存储枚举的类,如果枚举作为参数给出,它提供了一个函数以将这个枚举显示为字符串。

enum ErrorType: String {
    case InvalidInputTextFieldEmpty = "One or more inputs seem empty. Please enter your credentials."
    case InvalidInputPasswordsNotMatch = "Please check your passwords they doesn't seem to match."
}

class ErrorManager: NSObject {
    func handleError(errorType: ErrorType)
    {
        self.showAlertView(errorType.rawValue)
    }

    func showAlertView(message:String)
    {
        var alertView:UIAlertView = UIAlertView(title: "Notice", message: message, delegate: self, cancelButtonTitle: "OK")
        alertView.show()
    }
}

现在,我想使用以下方法访问另一个类中的handleError函数: ErrorManager.handleError(ErrorType.InvalidInputTextFieldEmpty)

但是,尽管我写了参数类型为ErrorType,但编译器抱怨如果类型为ErrorManager则参数为n0t。我在这里做错了什么?

米克·麦卡勒姆(Mick MacCallum)

当您将方法声明为实例方法时,您尝试将其作为类方法进行访问。您或者需要创建ErrorManager类的实例,并将其用作方法调用中的接收者,或者将您的方法声明更改为类方法,如下所示:

class ErrorManager: NSObject {
    class func handleError(errorType: ErrorType) {
        ErrorManager.showAlertView(errorType.rawValue)
    }

    class func showAlertView(message: String) {
        let alertView = UIAlertView(title: "Notice", message: message, delegate: self, cancelButtonTitle: "OK")
        alertView.show()
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章