Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

ios - How to use Objective-C code with #define macros in Swift

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What I did is to create a class method that returns the #define.

Example:

.h file:

#define AD_SIZE CGSizeMake(320, 50)
+ (CGSize)adSize;

.m file:

+ (CGSize)adSize { return AD_SIZE; }

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:

let size = YourClass.adSize()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...