【问题标题】:Swift enum as parameter in functionSwift枚举作为函数中的参数
【发布时间】:2015-01-10 14:13:24
【问题描述】:

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

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)

但是编译会抱怨参数是 n0t if kind ErrorManager 虽然我写的参数是类型 ErrorType。我在这里做错了什么?

【问题讨论】:

    标签: ios swift enums


    【解决方案1】:

    当您将方法声明为实例方法时,您正试图将其作为类方法访问。您要么需要创建 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()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多