I'm trying to use a third-party Objective-C library in a Swift project of mine. I have the library successfully imported into Xcode, and I've made a <Project>-Bridging-Header.h
file that's allowing me to use my Objective-C classes in Swift.
I seem to be running into one issue however: the Objective-C code includes a Constants.h
file with the macro #define AD_SIZE CGSizeMake(320, 50)
. Importing Constants.h
into my <Project>-Bridging-Header.h
doesn't result in a global constant AD_SIZE
that my Swift app can use.
I did some research and saw that the Apple documentation here under "Complex Macros" says that
“In Swift, you can use functions and generics to achieve the same results [as complex macros] without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.”
After reading that, I got it to work fine by specifying let AD_SIZE = CGSizeMake(320, 50)
in Swift, but I want to maintain future compatibility with the library in the event that these values change without me knowing.
Is there an easy fix for this in Swift or my bridging header? If not, is there a way to replace the #define AD_SIZE CGSizeMake(320, 50)
in Constants.h
and keep things backwards-compatible with any existing Objective-C apps that use the old AD_SIZE
macro?
write your constants after Class declaration. like this...
What I did is to create a class method that returns the #define.
Example:
.h file:
.m file:
And in Swift:
Since this is a class method you can now use it almost as you would the #define. If you change your #define macro - it will be reflected in the new method you created In Swift:
I resolved this by replacing
#define AD_SIZE CGSizeMake(320, 50)
in the library's
Constants.h
withextern CGSize const AD_SIZE;
and adding
CGSize const AD_SIZE = { .width = 320.0f, .height = 50.0f };
in the library's
Constants.m
file.