gpt4 book ai didi

objective-c - 如何在 Objective-C 中使用 Swift 结构

转载 作者:IT老高 更新时间:2023-10-28 11:22:46 26 4
gpt4 key购买 nike

我有一个存储应用程序常量的结构,如下所示:

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];

关于objective-c - 如何在 Objective-C 中使用 Swift 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26173234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com