ios - 从 Objective-C 文件快速访问常量

标签 ios objective-c iphone swift constants

我是 Swift 的新手。我有一个混合项目,其中一些类在 Objective-C 中,一些类在 Swift 中。我有一个基于 Objective-C 文件的 Constant.h 文件。在这个头文件中提到了一些常量,如下所示

#define mainViewBgColor [UIColor colorWithRed:248.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.0]

但问题是我无法在 Swift 类中访问此常量。请参阅下面的 Swift 代码

override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = mainViewBgColor //Want to access liek this but this line gives me an error.
        self.loadNavigation();
    }

请建议像这样访问常量的正确方法,特别是在 Objective-C 中写入常量。

注意:请考虑我有 Bridging-Header.h 文件,并且我已经将常量文件导入到该桥接文件中。即使我可以成功访问简单的字符串常量。

已编辑 替代解决方案:我发现在 swift 中使用常量的替代解决方案是创建新的 swift 常量文件,比如 SwiftConstant.swift 并在此文件中定义如下所示的常量。

let  mainViewBgColor = UIColor(red: 248.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)

现在无需在任何地方导入 SwiftConstant.swift 文件即可使用常量。我不知道这是正确的方法还是不希望并等待好的答案。

最佳答案

视情况而定。

来自文档

Simple Macros

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.

Complex Macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

来源:Using Swift with Cocoa and Objective-C

关于ios - 从 Objective-C 文件快速访问常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31957955/

相关文章:

objective-c - "Official"在 Objective-C 中引用类方法的语法?

iphone - 从 double 中删除最后 6 位数字(Objective-C)

IOS:如何在 UIWebview 中加载本地文件,例如:.png、.doc、.pdf 等

ios - 是否可以在 iOS 6/7 上自定义数字键盘中的左下角按钮?

iphone - viewDidAppear 用于 subview

ios - 使用物理体创建 SKSprite 节点的函数

ios - 使用 RestKit + CoreData 进行类设计

ios - VoIP 推送通知在装有 iOS 10.3 的 iPhone 7 上崩溃

ios - 核心数据一对多关系

iphone - 将 iPhone 应用程序转换为通用应用程序 : Grouped UITableView