Search code examples
swiftswift-protocolsconditional-compilation

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"?


Solution

  • Put it in an extension:

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