Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 873
ankushg Avatar asked Jun 10 '14 05:06

ankushg


People also ask

What can Objective-C be used for?

Objective-C is the primary programming language you use when writing software for OS X and iOS. It's a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime.

Is Objective-C compatible with C?

Objective-C is an object-oriented programming language that is a superset of C, as the name of the language might reveal. This means that any valid C program will compile with an Objective-C compiler. It derives all its non-object oriented syntax from C and its object oriented syntax from SmallTalk.

Does Apple still use Objective-C?

Although Objective-C is still supported by Apple, it has never been an open-source language.


1 Answers

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()

like image 140
YogevSitton Avatar answered Oct 01 '22 08:10

YogevSitton