Daniel Shin
Daniel Shin

Reputation: 5206

Restrict protocol extension to a single enum case

I'm trying to restrict extension to a protocol to a single case of enum only.

For example, this compiles:

extension FooProtocol where T == SomeEnum {}

But this doesn't:

extension FooProtocol where T == SomeEnum.CaseOne {}

I understand that this isn't possible since case in enum cannot be represented as a type by itself.

Is there a workaround to this?

Edit:

My case is something like the following:

extension SignalProducerType where E == AppError.NonError {
  func ignoreError() -> SignalProducer<T, NoError> {}
}

I wanted to expose ignoreError method only to those of which has an ErrorType as AppError.NonError (which is custom type)

Upvotes: 2

Views: 381

Answers (1)

Joseph Lord
Joseph Lord

Reputation: 6504

It depends on exactly what you are trying to achieve but in short not really. The type checker (and protocol conformance checking) happens at compile time and the case of the enum is generally only known at runtime.

You could define the method in the protocol extension to operate on the whole enum but return nil (or do nothing) for other cases.

Upvotes: 2

Related Questions