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

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

问题描述

我正在尝试在我的 Swift 项目中使用第三方 Objective-C 库.我已将库成功导入 Xcode,并制作了一个 <Project>-Bridging-Header.h 文件,该文件允许我在 Swift 中使用我的 Objective-C 类.

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 代码包含一个带有宏 #define AD_SIZE CGSizeMake(320, 50)Constants.h 文件.将 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) 并保持与任何现有 Objective-C 应用程序的向后兼容使用旧的 AD_SIZE 宏?

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?

推荐答案

我通过替换解决了这个问题

I resolved this by replacing

#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 文件中.

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

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