Search code examples
swiftxcodeenumsfunctional-programmingprotocols

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?


Solution

  • 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