【问题标题】:Compile-time conditional protocol conformance in SwiftSwift 中的编译时条件协议一致性
【发布时间】:2021-05-06 12:13:49
【问题描述】:

我有一个 Swift 类,在某些编译时条件下,它应该实现某个协议。我希望条件复杂化#if 检查会起作用,如下所示:

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

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

这不起作用。编译器尝试将每个条件块编译为一系列语句。但: SomeProtocol 块不会解析为一系列语句。

还有其他表达方式吗?例如,有没有语句级的方式来表达“MyClass implements SomeProtocol”?

【问题讨论】:

  • 定义一个 MyClass 扩展以符合协议并将所有这些都包含在您的编译时检查中

标签: swift swift-protocols conditional-compilation


【解决方案1】:

把它放在一个扩展中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多