Adding a case to an existing enum with a protocol

前端 未结 4 1296
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 04:40

I want to create a protocol that enforces a certain case on all enums conforming to this protocol.

For example, if I have a <

4条回答
  •  遥遥无期
    2020-12-15 05:42

    Here are a couple additional takes that may help somebody out there:

    Using your example:

    enum Foo {
        case bar(baz: String)
        case baz(bar: String)
    } 
    

    You can consider to "nest" it in a case of your own enum:

    enum FooExtended {
        case foo(Foo) // <-- Here will live your instances of `Foo`
        case fuzz(Int)
    }
    

    With this solution, it becomes more laborious to access the "hidden" cases associated type. But this simplification could actually be beneficial in certain applications.

    Another alternative passes by just recreate and extend it while having a way to convert Foo into the extended enum FooExtended (eg. with a custom init):

    enum FooExtended {
        case bar(baz: String)
        case baz(bar: String)
        case fuzz(Int)
    
        init(withFoo foo: Foo) {
            switch foo {
            case .bar(let baz):
                self =  .bar(baz: baz)
            case .baz(let bar):
                self = .baz(bar: bar)
            }
        }
    }
    

    There may be many places where one, the other, or both of these solutions make absolutely no sense, but I'm pretty sure they may be handy to somebody out there (even if only as an exercise).

提交回复
热议问题