jameshfisher
jameshfisher

Reputation: 36399

Compile-time conditional protocol conformance in Swift

I have a Swift class that, under certain compile-time conditions, should implement a certain protocol. I expected that conditional complication #if checks would work, with something like this:

class MyClass
#if SOME_COMPILE_TIME_CHECK
: SomeProtocol
#endif
{
  // ...

  #if SOME_COMPILE_TIME_CHECK
  func someMethodToImplementSomeProtocol() { }
  #endif
}

This does not work. The compiler tries to compile each conditional block as a series of statements. But the block : SomeProtocol does not parse as a series of statements.

Is there another way to express this? For example, is there a statement-level way to express that "MyClass implements SomeProtocol"?

Upvotes: 1

Views: 206

Answers (1)

Sweeper
Sweeper

Reputation: 270790

Put it in an extension:

#if SOME_COMPILE_TIME_CHECK
extension MyClass : SomeProtocol {
    func someMethodToImplementSomeProtocol() { }
}
#endif

Upvotes: 3

Related Questions