如何在Swift中使用带有#define宏的Objective-C代码 [英] How to use Objective-C code with #define macros in Swift

查看:973
本文介绍了如何在Swift中使用带有#define宏的Objective-C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的Swift项目中使用第三方Objective-C库。我已成功将库导入Xcode,并且我已经创建了一个< Project> -Bridging-Header.h 文件,该文件允许我使用我的Objective-C类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.

我似乎遇到了一个问题:Objective-C代码包含 Constants.h 文件与宏 #define AD_SIZE CGSizeMake(320,50)。将 Constants.h 导入我的< Project> -Bridging-Header.h 不会导致全局常量我的Swift应用程序可以使用的 AD_SIZE

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.

我做了一些研究,看到了Apple文档在复杂宏下

I did some research and saw that the Apple documentation here under "Complex Macros" says that


在Swift中,你可以使用函数和泛型来实现相同的
结果[作为复杂的宏],而不会有任何妥协。因此,C和Objective-C源文件中的
复杂宏不能用于你的Swift代码

"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."

阅读完之后,我通过在Swift中指定 let AD_SIZE = CGSizeMake(320,50)让它工作正常,但我希望保持未来的兼容性如果这些值在我不知情的情况下发生变化,那么使用库。

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.

在Swift或我的桥接头中是否有一个简单的解决方法?如果没有,有没有办法在 Constants.h 中替换 #define AD_SIZE CGSizeMake(320,50),保持向后兼容任何使用旧的 AD_SIZE 宏的现有Objective-C应用程序?

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?

推荐答案

我通过替换

#define AD_SIZE CGSizeMake(320,50)

在图书馆的 Constants.h

extern CGSize const AD_SIZE;

并添加

CGSize const AD_SIZE = {。width = 320.0f,.height = 50.0f};

在图书馆的 Constants.m file。

in the library's Constants.m file.

这篇关于如何在Swift中使用带有#define宏的Objective-C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆