如何在 Swift 中使用 Objective-C # 定义

我正在迁移一个 UIViewController类来训练一下 Swift。我通过桥接头成功地使用了 Objective-C 代码,但是我需要导入一个包含 #define指令的常量文件。

我在 与 Cocoa 和 Objective-C 一起使用 Swift(简单宏)中看到了以下内容:

简单宏

通常使用 #define指令在 C 和 Objective-C 中定义基本常量,而在 Swift 中使用全局常量。例如,使用 let FADE_ANIMATION_DURATION = 0.35可以更好地用 Swift 表示常量定义 #define FADE_ANIMATION_DURATION 0.35。因为简单的类常量宏直接映射到 Swift 全局变量,编译器自动导入在 C 和 Objective-C 源文件中定义的简单宏。

看来有可能。我已经将包含我的常量的文件导入到桥接头中,但是我的 .swift文件没有可见性,无法解析。

我该怎么做才能让斯威夫特看到我的常数呢?

更新:

它似乎可以使用 NSString常量,但不能使用布尔型:

#define kSTRING_CONSTANT @"a_string_constant" // resolved from swift
#define kBOOL_CONSTANT YES // unresolved from swift
103035 次浏览

At the moment, some #defines are converted and some aren't. More specifically:

#define A 1

...becomes:

var A: CInt { get }

Or:

#define B @"b"

...becomes:

var B: String { get }

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

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;

And then Swift will see:

var kSTRING_CONSTANT: NSString!
var kBOOL_CONSTANT: ObjCBool

Another option would be to change your BOOL defines to

#define kBOOL_CONSTANT 1

Faster. But not as good as actual constants.

Just a quick clarification on a few things from above.

Swift Constant are expressed using the keywordlet

For Example:

let kStringConstant:String = "a_string_constant"

Also, only in a protocol definition can you use { get }, example:

protocol MyExampleProtocol {
var B:String { get }
}

In swift you can declare an enum, variable or function outside of any class or function and it will be available in all your classes (globally)(without the need to import a specific file).

  import Foundation
import MapKit


let kStringConstant:String = "monitoredRegions"


class UserLocationData : NSObject {
class func getAllMonitoredRegions()->[String]{
defaults.dictionaryForKey(kStringConstant)
}

simple swift language don't need an macros all #define directives. will be let and complex macros should convert to be func

The alternative for macro can be global variable . We can declare global variable outside the class and access those without using class. Please find example below

import Foundation
let BASE_URL = "www.google.com"


class test {


}