Search code examples
iosobjective-cswiftbridge

Use #define constant put in Objective C .h file bridged in swift project


I'm working on a swift project and I have made MyProjectName-Bridging-header.h In this bridge, I have added a .h file that contains multiple constants made by

#define constantName VALUE

I need to know how to use these constants into my swift file?


Solution

  • Do not define constants with macros

    Using macros in place of global constants or functions is a sure sign of a code smell – they're not type-safe & can make debugging a nightmare. Thankfully, Swift does away with the C preprocessor, so you can no longer use them with Swift code!

    You should instead be defining constants in your Objective-C headers by using global C constants.

    static NSString* const aConstString = @"foobar";
    static NSInteger const aConstInteger = 42;
    

    Or if you want to keep the values out of your headers:

    extern NSString* const aConstString;
    extern NSInteger const aConstInteger;
    

    NSString* const aConstString = @"foobar";
    NSInteger const aConstInteger = 42;
    

    These will then get bridged over to a Swift global constants in your auto-generated Swift header and will look like this:

    public let aConstString: String
    public let aConstInteger: Int
    

    You can now access them from your Swift code.