简体   繁体   English

如何添加和使用枚举案例作为协议类型要求?

[英]How to add and use an Enum Case as a Protocol Type Requirement?

Context语境

I have multiple Enums conforming to a specific Protocol .我有多个符合特定ProtocolEnums I now would like to define a Custom Case for each of these Enums and use this Requirement for checking for Equality .我现在想为这些Enums中的每一个定义一个Custom Case并使用这个Requirement来检查Equality However, I get the following Compiler Error :但是,我收到以下Compiler Error

'var' binding pattern cannot appear in an expression 'var' 绑定模式不能出现在表达式中


Code代码

protocol Component {
    // I read that you can use this Syntax for requiring Enum Cases -> It is working!
    static var default: Self { get }
    static func custom(value: Int) -> Self

    var customValue: Int? { get }
}

extension Component {
    var customValue: Int? {
        guard case .custom(let value) = self else { return nil } // Compiler Error in this Line.
        return value
    }
}

Question问题

How can I achieve my goal of not only requiring Cases but also working with them and checking for Equality ?我如何才能实现不仅需要Cases还要使用它们并检查Equality的目标?

You can't require protocol conformances to be enum's你不能要求协议一致性是枚举的

protocol Component {
    static var `default`: Self { get }
    static func custom(value: Int) -> Self

    var customValue: Int? { get }
}

struct C: Component {
    static var `default`: C {
        return C()
    }

    static func custom(value: Int) -> Self {
        return C()
    }

    var customValue: Int? { 42 }
}

let c = C()
c is Component // true

And because you can't require conforming types to be enums you can't switch/case on self in a protocol extension而且因为你不能要求符合类型是枚举,所以你不能在协议扩展中对 self 进行 switch/case

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM