在目标 C 中使用 #define 并在 swift 类中访问 [英] use #define in objective C and access in swift class

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

问题描述

我在目标 c 类中定义了 #define baseUrl [NSString stringWithFormat:@"%@api/v4", MAINURL] 并且可以访问项目中的任何地方.但是现在我已经在退出的目标 c 项目中创建了 swift 文件,并想快速访问 baseurl 但收到错误.

I have define #define baseUrl [NSString stringWithFormat:@"%@api/v4", MAINURL] in objective c class and can access anywhere in project. But now i have created swift file in exiting objective c project and want to access baseurl in swift but error received.

Use of unresolved identifier 'baseUrl'

如何解决?

推荐答案

将 Objective-C 宏导入 Swift 并不总是有效.根据文档:

Importing Objective-C macros into Swift doesn't always work. According to documentation:

Swift 自动导入简单的、类似常量的宏,用 #define 指令声明,作为全局常量.当宏使用字面量表示字符串、浮点数或整数值,或者在字面量或先前定义的宏之间使用 +、-、> 和 == 等运算符时,就会导入宏.

Swift automatically imports simple, constant-like macros, declared with the #define directive, as global constants. Macros are imported when they use literals for string, floating-point, or integer values, or use operators like +, -, >, and == between literals or previously defined macros.

比简单常量定义更复杂的 C 宏在 Swift 中没有对应物.

在您的情况下,另一种方法是使用返回宏定义的值的函数

An alternative in your case would be to use a function that returns the value defined by macro

// .h file
#define baseUrl [NSString stringWithFormat:@"%@api/v4", MAINURL]
+ (NSString*) BaseUrl;

// .m file
+ (NSString*) BaseUrl { return baseUrl }

这篇关于在目标 C 中使用 #define 并在 swift 类中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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