Reputation: 976
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.
Upvotes: 8
Views: 3354
Reputation: 61
You can use #if canImport(ModuleName) in Swift 4.
#if canImport(UIkit)
import UIKit
#elseif canImport(MyBus)
import MyBus
#else
// Workaround/text, whatever
#endif
Upvotes: 6
Reputation: 6622
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.
Upvotes: 0