简体   繁体   中英

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

Context

I have multiple Enums conforming to a specific Protocol . I now would like to define a Custom Case for each of these Enums and use this Requirement for checking for Equality . However, I get the following Compiler Error :

'var' binding pattern cannot appear in an expression


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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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