如何在Swift中使用Objective-C #define [英] How to use a Objective-C #define from Swift

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

问题描述

我正在迁移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.

我在将Swift与可可一起使用和Objective-C (简单宏)如下:

简单宏

通常在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 #defines are converted and some aren't. More specifically:

#define A 1

...成为:

var A: CInt { get }

或者:

#define B @"b"

...成为:

var B: String { get }

不幸的是,Swift编译器无法实时识别和转换YESNO.

Unfortunately, YES and NO aren't recognized and converted on the fly by the Swift compiler.

我建议您将#define转换为实际常量,无论如何都要好于#define.

I suggest you convert your #defines to actual constants, which is better than #defines 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屋!

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