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

我有一个协议
protocol P { }

它由枚举实现

enum E: P {
    case a
    case b
}

到现在为止还挺好.

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

我试过这个:

extension P {

    var value: String {
        switch self {
            case E.a: return "This is an E.a"
            default: return "meh"
        }
    }
}

但这不编译

error: Temp.playground:14:16: error: enum case 'a' is not a member of type 'Self'
    case E.a: return "hello"

我也尝试过:

case is E.a: return "This is an E.a"

这只是给出了这个错误:

error: Temp.playground:14:19: error: enum element 'a' is not a member type of 'E'
     case is E.a: return "hello"
             ~ ^

我知道我可以这样做:

switch self {
    case let e as E:
        switch e {
            case E.a: return "hello"
            default: return "meh"
        }
    default: return "meh"
}

但我真的不想要!

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

你需要匹配类型E才能测试
值E.a,但这可以在一个表达式中完成:
extension P {    
    var value: String? {
        switch self {
        case let e as E where e == .a:
            return "hello"
        default:
            return nil
        }
    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...