如何在 Objective-C 中使用 Swift 结构 [英] How to use Swift struct in Objective-C

查看:33
本文介绍了如何在 Objective-C 中使用 Swift 结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Simply I have a struct that stores the application constants as below:

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 代码中使用这些常量?

These constants can be use in Swift code by calling Constant.ParseClientKey for example. But in my code, it also contains some Objective-C classes. So my question is how to use these constants in the Objective-C code?

如果这种声明常量的方式不好,那么创建用于 Swift 和 Objective-C 代码的全局常量的最佳方式是什么?

If this way to declare constants is not good then what is the best way to create global constants to be used in both Swift and Objective-C code?

推荐答案

很遗憾,你不能将 struct 和全局变量暴露给 Objective-C.请参阅文档,其中部分说明:

Sad to say, you can not expose struct, nor global variables to Objective-C. see the documentation, which states in part:

在需要 Objective-C 互操作性时使用类

Use Classes When You Need Objective-C Interoperability

如果您使用需要处理数据的 Objective-C API,或者您需要将数据模型适合在 Objective-C 框架中定义的现有类层次结构中,您可能需要使用类和类继承来建模你的数据.例如,许多 Objective-C 框架公开了您希望子类化的类.

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.

到目前为止,恕我直言,最好的方法是这样的:

As of now, IMHO, the best way is something like this:

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 中,你可以像这样使用它们:

In Objective-C, you can use them like this:

NSString *appklicationId = [Constant parseApplicationId];
NSString *clientKey = [Constant parseClientKey];
UIColor *greenColor = [Constant appGreenColor];

这篇关于如何在 Objective-C 中使用 Swift 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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