简体   繁体   中英

Accessing Objective-C #define constant from Swift

I have an existing project with Swift and Objective C.h and.m files. In one of the.h files are numerous

#define kSomeConstant @"some string"

How can I make these available to Swift files in the project when the Swift file is in a framework that is a subproject of the app?

So far I've tried making wrapper static methods in the.m file class definition such as:

+ (NSString*) objc_kSomeConstant { return kSomeConstant; }

And I've tried doing something like the following in the.h:

extern NSString *const kSomeConstant;

with the definition in the.m file:

NSString *const kSomeConstant = @"some string"

Neither way has worked.

To be clear, you have some definitions in an Objective-C header file in the main application target of your project, and you want to make them available to a Swift file in a framework target which is a subproject of your main project. Normally your application depends on definitions in the framework, not the other way around. To share these definitions between the application and the framework, create a clang compiler module that can be used by both.

To do this, move the header with the definitions into a folder (which we'll call "Common"), and in this folder create a file called "module.modulemap" which contains the following:

module Common {
    header "CommonDefinitions.h"
}

Next, in your framework target, set the Import Paths setting (under Swift Compiler - Search Paths ) to the path of this folder ( eg , $(SRCROOT)/Common ). You may need to add this folder to the Header Search Paths setting of your main application as well, so that it will continue to compile successfully.

Now the definitions can be accessed from the Swift files in the framework by simply adding the statement import Common . (Note that names #define d as Objective-C string literals, like kSomeConstant in your example, are imported into Swift as String constants; there should be no need to rewrite them as extern NSString * declarations.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM