6

I have defined some constants in my .m files that I need to access form my swift code. They are defined:

const CGFloat testValue = 40.0;

and in my other objective-c .m files I can access them by using extern:

extern const CGFloat testValue

Is there an equivalent way of making these constants accessible from the .swift files?

Shruti Thombre
  • 989
  • 4
  • 11
  • 27
reza23
  • 3,079
  • 2
  • 27
  • 42
  • Take a look at this page: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html –  Sep 05 '14 at 15:45

2 Answers2

15

Add the extern to your bridging header and Swift should be able to access it.

This simple test worked for me:

ObjCTest.m

#import <Foundation/Foundation.h>

const CGFloat testValue = 40.0;

ObjCSwiftBridgeTest-Bridging-Header.h

#import <Foundation/Foundation.h>

extern const CGFloat testValue;

main.swift

println(testValue);

Output

40.0
Mike S
  • 41,895
  • 11
  • 89
  • 84
  • Side note: If it's an object (e.g. a String), I had to remove the keyword "static" for it to work. – StuFF mc Dec 05 '14 at 14:11
  • 2
    That's strange, I have mine defined in a `.h` and imported that via the bridging header but it wouldn't work. Redefining it explicitly in the bridging header fixes it. You'd think that's the point of importing?? Seems like a bug. – Chris Wagner Jan 27 '15 at 21:02
  • I only have to have the `extern` in Xcode 7.3.0. For some reason, Xcode 7.3.1 and 7.2.1 both work fine. – Anthony Elliott May 16 '16 at 19:53
0

Just put the var declaration above the class - it will become a global variable.

Mundi
  • 79,884
  • 17
  • 117
  • 140