Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift's canImport analogue in Objective-C

Swift 4.2 has a special condition canImport that helps developers to check whether a module can be imported in project. It was introduced in Swift 4.1.

Now I am working on iOS project written in Objective-C. I use modules, and for each target these modules are different. That's why I want to use something like that:

#if canImport(SomeModule)
@import SomeModule;
#endif

How can I solve this problem? Now I use different "Other C Flags" for each target, but I want to find more flexible solution.

like image 567
Roman Podymov Avatar asked Oct 02 '18 09:10

Roman Podymov


People also ask

Can we use Swift code in Objective-C?

You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.

Which feature allows users to check if a tested module was available on a certain platform?

How to check whether a module is available using canImport() Writing multi-platform code has its own challenges, but if you use the canImport() compiler test then one big challenge is solved for you: you can write one chunk code to run if a specific module is available, and another chunk otherwise.


1 Answers

This is a little late as an answer, but i came across this issue while working on a similar case. I used the __has_include(<SomeModule/SomeModule.h>)

Importing your framework:

#if __has_include(<SomeModule/SomeModule.h>)
#import <SomeModule/SomeModule.h>
#define __HAS_SOME_MODULE_FRAMEWORK__
#endif

Later in your code :

- (void)doSomething {
    #ifdef __HAS_SOME_MODULE_FRAMEWORK__
    // with  SomeModule framework
    #else
    // without  SomeModule framework
    #endif
}
like image 185
spencer Avatar answered Sep 21 '22 09:09

spencer