简体   繁体   English

如何在Swift中的扩展错误类上具有不同的枚举?

[英]How can I have different enums on an extended error class in Swift?

I am trying to make a "base" error, that does all the things I want to do for all my errors, and then extend it for each error to have different ErrorType s. 我试图制造一个“基本”错误,该错误针对所有错误执行我想做的所有事情,然后针对每个错误将其扩展为具有不同的ErrorType I know that I can't really extend an enum , so I have no idea how I'd be able to accomplish something like this. 我知道我不能真正扩展一个enum ,所以我不知道如何实现这样的目标。 Below is my current code. 下面是我当前的代码。

class BaseError: Error {
    enum ErrorType {}

    typealias Context = [String:Any]?;

    private let type: ErrorType
    private let context: Context;
    private let line: Int;
    private let function: String;
    private let file: String;

    init(
        type: ErrorType,
        context: Context,
        line: Int = #line,
        file: String = #file,
        function: String = #function
        ) {
        self.type = type;
        self.context = context;
        self.line = line;
        self.function = function;
        self.file = file;


    }

}

class MyError: BaseError {
    enum ErrorType {
        case noApp
        case noLabel
    }
}

I'd want to do something like throw A11yError(type: .noApp) . 我想做一些类似throw A11yError(type: .noApp) Doing that now just tells me Type 'BaseError.ErrorType' has no member 'noApp' . 现在,这样做只是告诉我Type 'BaseError.ErrorType' has no member 'noApp'

Have you considered using generics to inject the ErrorType ? 您是否考虑过使用泛型注入ErrorType

class BaseError<ErrorType>: Error {

    typealias Context = [String:Any]?;

    private let type: ErrorType
    private let context: Context;
    private let line: Int;
    private let function: String;
    private let file: String;

    init(
        type: ErrorType,
        context: Context,
        line: Int = #line,
        file: String = #file,
        function: String = #function
        ) {
        self.type = type;
        self.context = context;
        self.line = line;
        self.function = function;
        self.file = file;


    }

}

enum MyError {
    case noApp
    case noLabel
}


let error = BaseError(type: MyError.noApp, context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM