简体   繁体   English

Swift 中的编译时条件协议一致性

[英]Compile-time conditional protocol conformance in Swift

I have a Swift class that, under certain compile-time conditions, should implement a certain protocol.我有一个 Swift class 在某些编译时条件下,应该实现某个协议。 I expected that conditional complication #if checks would work, with something like this:我预计条件复杂#if检查会起作用,如下所示:

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.但是 block : SomeProtocol不会解析为一系列语句。

Is there another way to express this?有没有另一种表达方式? For example, is there a statement-level way to express that " MyClass implements SomeProtocol "?例如,是否有一种语句级的方式来表达“ MyClass implements SomeProtocol ”?

Put it in an extension:把它放在一个扩展中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM