How to use a Objective-C #define from Swift
In swift you can declare an enum, variable or function outside of any class or function and it will be available in all your classes (globally)(without the need to import a specific file).
import Foundation
import MapKit
let kStringConstant:String = "monitoredRegions"
class UserLocationData : NSObject {
class func getAllMonitoredRegions()->[String]{
defaults.dictionaryForKey(kStringConstant)
}
Just a quick clarification on a few things from above.
Swift Constant are expressed using the keywordlet
For Example:
let kStringConstant:String = "a_string_constant"
Also, only in a protocol definition can you use { get }
, example:
protocol MyExampleProtocol {
var B:String { get }
}
At the moment, some #define
s are converted and some aren't. More specifically:
#define A 1
...becomes:
var A: CInt { get }
Or:
#define B @"b"
...becomes:
var B: String { get }
Unfortunately, YES
and NO
aren't recognized and converted on the fly by the Swift compiler.
I suggest you convert your #define
s to actual constants, which is better than #define
s anyway.
.h:
extern NSString* const kSTRING_CONSTANT;
extern const BOOL kBOOL_CONSTANT;
.m
NSString* const kSTRING_CONSTANT = @"a_string_constant";
const BOOL kBOOL_CONSTANT = YES;
And then Swift will see:
var kSTRING_CONSTANT: NSString!
var kBOOL_CONSTANT: ObjCBool
Another option would be to change your BOOL
defines to
#define kBOOL_CONSTANT 1
Faster. But not as good as actual constants.