我有一个存储应用程序常量的结构,如下所示:
struct Constant {
static let ParseApplicationId = "xxx"
static let ParseClientKey = "xxx"
static var AppGreenColor: UIColor {
return UIColor(hexString: "67B632")
}
}
这些常量可以通过调用 Constant.ParseClientKey
在 Swift 代码中使用。但在我的代码中,它还包含一些 Objective-C 类。所以我的问题是如何在 Objective-C 代码中使用这些常量?
如果这种声明常量的方式不好,那么创建用于 Swift 和 Objective-C 代码的全局常量的最佳方式是什么?
最佳答案
遗憾的是,您不能将 struct
或全局变量暴露给 Objective-C。见 the documentation ,其中部分说明:
Use Classes When You Need Objective-C Interoperability
If you use an Objective-C API that needs to process your data, or you need to fit your data model into an existing class hierarchy defined in an Objective-C framework, you might need to use classes and class inheritance to model your data. For example, many Objective-C frameworks expose classes that you are expected to subclass.
到目前为止,恕我直言,最好的方法是这样的:
let ParseApplicationId = "xxx"
let ParseClientKey = "xxx"
let AppGreenColor = UIColor(red: 0.2, green: 0.7, blue: 0.3 alpha: 1.0)
@objc class Constant: NSObject {
private init() {}
class func parseApplicationId() -> String { return ParseApplicationId }
class func parseClientKey() -> String { return ParseClientKey }
class func appGreenColor() -> UIColor { return AppGreenColor }
}
在 Objective-C 中,你可以像这样使用它们:
NSString *appklicationId = [Constant parseApplicationId];
NSString *clientKey = [Constant parseClientKey];
UIColor *greenColor = [Constant appGreenColor];
https://stackoverflow.com/questions/26173234/
相关文章:
ios - 在 UIView 上设置 alpha 会在其 subview 上设置不应该发生的 alp
objective-c - ARC : strong or retain? 的@property 定
iphone - UITableView 单元格中的 UISwitch
objective-c - Objective-C 中的字符串比较
ios - 为什么masksToBounds = YES会阻止CALayer阴影?
iphone - 如何为 View 或图像沿弯曲路径的移动设置动画?
ios - 如何使用 UISegmentedControl 切换 View ?
objective-c - Xcode 7.3 无法使用手动引用计数在文件中创建 __weak 引用