Can an enum conform to a protocol using its cases?

Using Swift 4.2:

protocol Foo {
    static func bar() -> Self
}

enum Bar: Foo { // error: Type 'Bar' does not conform to protocol 'Foo'
    case bar
}

When I apply the fix-it...

protocol Foo {
    static func bar() -> Self
}

enum Bar: Foo {
    case bar

    static func bar() -> Bar { // error: Invalid redeclaration of 'bar()'
        return .bar
    }
}

Is there a reason this doesn't work?

I think it should work but it's not implemented yet. Similarly, you would expect an empty case to be able to witness a static property requirement. Fixing this is tracked by [SR-3170] Enum cases should satisfy static var {get} protocol requirements · Issue #45758 · apple/swift · GitHub -- it would be a good not-quite-starter bug for someone to figure out. There are two stages here, the first is to get the type checker to accept the conformance, the second is to fix SILGen to emit the witness thunk correctly (this may or may not be required; I don't remember offhand if we assume the witness is always a function or not).

7 Likes

This is because enum cases especially cases with associated values, are usually noncallable functions while that method protocol requirement is a callable one