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

查看:64
本文介绍了如何在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?

推荐答案

不幸的是,可以不暴露,也不Objective-C的全局变量.参见文档.

Sad to say, you can not expose struct, nor global variables to Objective-C. see the documentation.

截至目前,恕我直言,最好的方法是这样的:

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天全站免登陆