当枚举实现协议时,在switch中匹配枚举值

dea*_*rne 6 switch-statement swift

我有一个协议

protocol P { }
Run Code Online (Sandbox Code Playgroud)

它由枚举实现

enum E: P {
    case a
    case b
}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.

我希望能够接收实例P,并返回一个特定值,如果它是E(将来会有其他枚举/结构等实现P).

我试过这个:

extension P {

    var value: String {
        switch self {
            case E.a: return "This is an E.a"
            default: return "meh"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不编译

error: Temp.playground:14:16: error: enum case 'a' is not a member of type 'Self'
    case E.a: return "hello"
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

 case is E.a: return "This is an E.a"
Run Code Online (Sandbox Code Playgroud)

这只是给出了这个错误:

 error: Temp.playground:14:19: error: enum element 'a' is not a member type of 'E'
     case is E.a: return "hello"
             ~ ^
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

switch self {
    case let e as E:
        switch e {
            case E.a: return "hello"
            default: return "meh"
        }
    default: return "meh"
}
Run Code Online (Sandbox Code Playgroud)

但我真的不想要!

我缺少一种语法或技巧吗?

Mar*_*n R 8

E在测试值之前,需要匹配类型E.a,但这可以在单个表达式中完成:

extension P {    
    var value: String? {
        switch self {
        case let e as E where e == .a:
            return "hello"
        default:
            return nil
        }
    }
}
Run Code Online (Sandbox Code Playgroud)