8

In objective-c, I have something like:

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

How can we check if a class exists in swift? This link has some answer Weak Linking - check if a class exists and use that class

The good thing about __has_include is that it is a compile time check, but it only works for objective-c header. Do we have anything works for swift? Or maybe what I am doing is not a good approach?

For example, I have a class Machine and it has a method Gun, if I have included a Pistol framework, it will return Pistol. If I have included both Pistol and AK47, it will return AK47, cause it has more bullets.

Community
  • 1
  • 1
Zitao Xiong
  • 956
  • 1
  • 10
  • 18
  • Swift 4.1 is coming with new check `canImport`. [Proposal](https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md) – dispatchMain Feb 15 '18 at 04:31

2 Answers2

5

You can use #if canImport(ModuleName) in Swift 4.

    #if canImport(UIkit)
       import UIKit
    #elseif canImport(MyBus)
       import MyBus
    #else
      // Workaround/text, whatever
    #endif
Ankit garg
  • 51
  • 1
  • 4
  • Note that this only works with Modules. It won't work for example to check if an optional cocoapods subspec is available or if a specific class can be used. Which means that it isn't really an option for features unless they are packed as a separate module. – Daniel Nov 25 '22 at 10:37
0

Compile time checks are still available in Swift, but they are much less robust. In order to achieve the compile time checking, you'll need to define a compilation condition and setup some new build configurations which can have the conditions enabled or disabled. Swift doesn't have a preprocessor (yet?), so this is the extent of your ability.

allenh
  • 6,582
  • 2
  • 24
  • 40