swift – 当枚举实现协议时,在switch中匹配枚举值
发布时间:2020-12-14 05:39:06  所属栏目:百科  来源:网络整理 
            导读:我有一个协议 protocol P { } 它由枚举实现 enum E: P { case a case b} 到现在为止还挺好. 我希望能够接收P的实例,并返回一个特定值,如果它是E之一(将来会有其他枚举/结构等实现P). 我试过这个: extension P { var value: String { switch self { case E.a
                
                
                
            | 
                         
 我有一个协议 
  
  
  
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
        }
    }
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
