枚举

时间:2015-12-03 10:11:03

标签: swift enums swift2 protocols

这是我的代码:

protocol Logable {
    func log()
}

extension Logable where Self: Error {
    func log() {
        switch self {
        case .Server(code: Int, message: String):
            print("code = \(code), message = \(message)")
        }
    }
}

enum Error: Logable {
    case Client(code: Int, message: String)
    case Server(code: Int, message: String)
}

如您所见,我想为我的枚举LogableError创建协议Error的默认实现。也许它不可能 - 请提供链接。不要在操场上运行它,它不会显示任何内容,但编译器会给出错误: type 'Self' constrained to non-protocol type 'Error'

1 个答案:

答案 0 :(得分:3)

如果您想为Logable实施Error,则不需要协议扩展,只需要Error上的扩展名。

protocol Logable {
    func logError()
}

enum Error {
    case Client(code: Int, message: String)
    case Server(code: Int, message: String)
}

extension Error : Logable {
    func logError() {
        switch self {
            case .Client(let code, let message):
                print("code = \(code), message = \(message)")

            case .Server(let code, let message):
                print("code = \(code), message = \(message)")
        }
    }
}