我有一个协议
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,但这可以在一个表达式中完成:
值E.a,但这可以在一个表达式中完成:
extension P {
var value: String? {
switch self {
case let e as E where e == .a:
return "hello"
default:
return nil
}
}
}