Not allowing to use Constant defined in Objective C header file in swift class. Undefined symbols for architecture armv7

两盒软妹~` 提交于 2019-11-29 09:20:36

Update:

As of Swift 2/Xcode 7 and later, a static constant definition like

static NSString* const kColor005C98 = @"005C98"; // in Constants.h file

is imported to Swift and can be used without problems.


(Old answer for Swift 1.x) When the code

static NSString* const kColor005C98 = @"005C98"; // in Constants.h file

is processed by an Objective-C compiler, it is treated as two things combined into one statement:

  • A variable declaration which introduces an identifier and describes its type, and
  • a variable definition which actually instantiates/implements this identifier.

See for example What is the difference between a definition and a declaration? for a good explanation of the difference between declaration and definition.

The Swift compiler treats the statement only as a declaration. Therefore the variable is not defined anywhere, causing the linker error.

To solve the problem, you have to move the definition to an Objective-C file:

// Constants.m:
#import "Constants.h"
NSString * const kColor005C98  = @"005C98";

and change the declaration to an extern declaration:

// Constants.h:
extern NSString * const kColor005C98;

Alternatively, you can just remove the static modifier:

 NSString * const kColor005C98 = @"005C98";

to make it work with Swift. The disadvantage is that when this line is included by multiple Objective-C files, all of them will define a globally visible symbol kColor005C98, causing "duplicate symbol" linker errors.

Another alternative is to use a macro definition instead:

#define kColor005C98 @"005C98"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!