如何在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.
我在
简单宏
通常在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
转换为实际常量,无论如何都要好于#define
.
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屋!