How to use a Objective-C #define from Swift

At the moment, some #defines are converted and some aren’t. More specifically:

#define A 1

…becomes:

var A: CInt { get }

Or:

#define B @"b"

…becomes:

var B: String { get }

Unfortunately, YES and NO aren’t recognized and converted on the fly by the Swift compiler.

I suggest you convert your #defines to actual constants, which is better than #defines anyway.

.h:

extern NSString* const kSTRING_CONSTANT;
extern const BOOL kBOOL_CONSTANT;

.m

NSString* const kSTRING_CONSTANT = @"a_string_constant";
const BOOL kBOOL_CONSTANT = YES;

And then Swift will see:

var kSTRING_CONSTANT: NSString!
var kBOOL_CONSTANT: ObjCBool

Another option would be to change your BOOL defines to

#define kBOOL_CONSTANT 1

Faster. But not as good as actual constants.

Leave a Comment