Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__has_include check a class exists against swift?

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.

like image 670
Zitao Xiong Avatar asked Jul 21 '16 21:07

Zitao Xiong


Video Answer


1 Answers

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

    #if canImport(UIkit)
       import UIKit
    #elseif canImport(MyBus)
       import MyBus
    #else
      // Workaround/text, whatever
    #endif
like image 74
Ankit garg Avatar answered Sep 20 '22 21:09

Ankit garg