Reputation: 2784
I am very new to Swift. I have one hybrid project in which some classes are in Objective-C and some are Swift. I have one Constant.h file which is based with Objective-C file. In this header file have mention some constant like bellow
#define mainViewBgColor [UIColor colorWithRed:248.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.0]
But problem is that i can't access this constant in Swift class. See bellow Swift code
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = mainViewBgColor //Want to access liek this but this line gives me an error.
self.loadNavigation();
}
Please suggest the right way to access constants like this specifically the constant write in Objective-C.
Note : Please consider that i have Bridging-Header.h file and i have already import the constant file into that bridge file. Even i can successfully access simple string constant.
Edited Alternate Solution : I have found the alternate solution for using constants in swift is to create new swift constant file let say SwiftConstant.swift and define the constant like bellow in this file.
let mainViewBgColor = UIColor(red: 248.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)
now without importing SwiftConstant.swift file anywhere i can use the constant. i don't know this is right way or not hoping and wait for good answer.
Upvotes: 6
Views: 3153
Reputation: 285059
It depends.
From the documentation
Simple Macros
Where you typically used the #define directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead. For example, the constant definition #define FADE_ANIMATION_DURATION 0.35 can be better expressed in Swift with let FADE_ANIMATION_DURATION = 0.35. Because simple constant-like macros map directly to Swift global variables, the compiler automatically imports simple macros defined in C and Objective-C source files.
Complex Macros
Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.
Source: Using Swift with Cocoa and Objective-C
Upvotes: 4