【问题标题】:__has_include check a class exists against swift?__has_include 检查是否存在针对 swift 的类?
【发布时间】:2018-06-04 19:12:40
【问题描述】:

在objective-c中,我有类似的东西:

#if __has_include(<MyFramework/SomeFeature.h>)
SomeFeature *h = [SomeFeature new]
#else
OtherFeature *h = [OtherFeature new]
#endif

我们如何快速检查一个类是否存在?这个链接有一些答案Weak Linking - check if a class exists and use that class

__has_include 的好处是它是编译时检查,但它只适用于 Objective-c 头文件。我们有什么适用于 swift 的吗?或者也许我正在做的不是一个好方法?

例如,我有一个类Machine,它有一个方法Gun,如果我包含了一个Pistol 框架,它将返回Pistol。如果我同时包含了Pistol 和AK47,它将返回AK47,因为它有更多的子弹。

【问题讨论】:

  • Swift 4.1 即将推出新支票canImport。 Proposal

标签: ios objective-c swift


【解决方案1】:

您可以在 Swift 4 中使用 #if canImport(ModuleName)。

    #if canImport(UIkit)
       import UIKit
    #elseif canImport(MyBus)
       import MyBus
    #else
      // Workaround/text, whatever
    #endif

【讨论】:

    【解决方案2】:

    编译时检查在 Swift 中仍然可用,但它们的健壮性要低得多。为了实现编译时检查,您需要定义一个compilation condition 并设置一些新的build configurations 可以启用或禁用条件。 Swift 没有预处理器(还没有?),所以这就是你的能力范围。

    【讨论】:

      猜你喜欢
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多