ios - Swift 枚举作为函数中的参数

标签 ios swift enums

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

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 类型。我在这里做错了什么?

最佳答案

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

关于ios - Swift 枚举作为函数中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877132/

相关文章:

c# - Xamarin IOS 对 Base64 图像进行编码/解码

Swift4:新的 Codable 协议(protocol)问题

swift - 使用关联值时获取枚举名称

.net - 如何将枚举参数从组合框传递到另一个类(winform)

ios - 使用 Alamofire (Swift 2) 从 JSON 填充表格 View 单元格

wpf - 在设置中存储单选按钮选择

ios - 如何在 Swift 2.0 中将 UITextField 转换为整数?

ios - UITableViewDelegate 无法工作并出现错误( fatal error : Unexpectedly found nil while unwrapping an Optional value in UITableView in swift 4)

iphone - 丰富的 UITextView 中不显示文本属性 (iOS 6)

swift - iOS Swift - 如何使用 CABasicAnimation 和 CATransform3DRotate 以及 "m34"变换来制作 360 度翻转动画?