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") } }
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?
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?
Swift's Struct type is one of the most praised features of the language, but is currently unavailable in Objective-C.
A struct definition is just a blueprint. To use a struct, we need to create an instance of it. For example, struct Person { var name = " " var age = 0 } // create instance of struct var person1 = Person() Here, we have created an instance by writing the name of the structure Person followed by a default initializer ()
Alternatively, you can create a bridging header yourself by choosing File > New > File > [operating system] > Source > Header File. Edit the bridging header to expose your Objective-C code to your Swift code: In your Objective-C bridging header, import every Objective-C header you want to expose to Swift.
Sad to say, you can not expose struct
, nor global variables to Objective-C. see the documentation, which states in part:
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.
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 } }
In Objective-C, you can use them like this:
NSString *appklicationId = [Constant parseApplicationId]; NSString *clientKey = [Constant parseClientKey]; UIColor *greenColor = [Constant appGreenColor];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With