如何在 Swift 中使用 Objective-C #define [英] How to use a Objective-C #define from Swift
问题描述
我正在迁移一个 UIViewController
类以使用 Swift 进行一些训练.我通过桥接头成功使用了 Objective-C 代码,但我需要导入一个包含 #define
指令的常量文件.
I am migrating a UIViewController
class to train a bit with Swift. I am successfully using Objective-C code via the bridging header but I have the need of importing a constants file that contains #define
directives.
我在 Using Swift with Cocoa 中看到了和Objective-C(简单宏)如下:
I have seen in Using Swift with Cocoa and Objective-C (Simple macros) the following:
简单宏
在 C 和 Objective-C 中通常使用 #define
指令来定义原始常量,而在 Swift 中则使用全局常量.例如,常量定义 #define FADE_ANIMATION_DURATION 0.35
可以用 Swift 更好地表示为 let FADE_ANIMATION_DURATION = 0.35
.因为简单的类常量宏直接映射到 Swift 全局变量,所以编译器会自动导入在 C 和 Objective-C 源文件中定义的简单宏.
Where you typically used the #define
directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead. For example, the constant definition #define FADE_ANIMATION_DURATION 0.35
can be better expressed in Swift with let FADE_ANIMATION_DURATION = 0.35
. Because simple constant-like macros map directly to Swift global variables, the compiler automatically imports simple macros defined in C and Objective-C source files.
所以,这似乎是可能的.我已将包含我的常量的文件导入到桥接头中,但我的 .swift
文件没有可见性,无法解析.
So, it seems it's possible. I have imported the file containing my constants into the bridging header, but I have no visibility from my .swift
file, cannot be resolved.
我应该怎么做才能让我的常量对 Swift 可见?
What should I do to make my constants visible to Swift?
更新:
似乎可以使用 NSString
常量,但不能使用布尔值:
It seems working with NSString
constants, but not with booleans:
#define kSTRING_CONSTANT @"a_string_constant" // resolved from swift
#define kBOOL_CONSTANT YES // unresolved from swift
推荐答案
目前,一些 #define
被转换,一些没有.更具体地说:
At the moment, some #define
s are converted and some aren't. More specifically:
#define A 1
...变成:
var A: CInt { get }
或者:
#define B @"b"
...变成:
var B: String { get }
很遗憾,Swift 编译器无法识别和转换 YES
和 NO
.
Unfortunately, YES
and NO
aren't recognized and converted on the fly by the Swift compiler.
我建议你将你的 #define
s 转换为实际的常量,这比 #define
s 好.
I suggest you convert your #define
s to actual constants, which is better than #define
s anyway.
.h:
extern NSString* const kSTRING_CONSTANT;
extern const BOOL kBOOL_CONSTANT;
.m
NSString* const kSTRING_CONSTANT = @"a_string_constant";
const BOOL kBOOL_CONSTANT = YES;
然后 Swift 会看到:
And then Swift will see:
var kSTRING_CONSTANT: NSString!
var kBOOL_CONSTANT: ObjCBool
另一种选择是将您的 BOOL
定义更改为
Another option would be to change your BOOL
defines to
#define kBOOL_CONSTANT 1
更快.但不如实际常量.
Faster. But not as good as actual constants.
这篇关于如何在 Swift 中使用 Objective-C #define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!